DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • DevOps in Legacy Systems
  • Microservices With Apache Camel and Quarkus (Part 3)
  • Decoding eBPF Observability: How eBPF Transforms Observability as We Know It
  • What to Pay Attention to as Automation Upends the Developer Experience

Trending

  • DevOps in Legacy Systems
  • Microservices With Apache Camel and Quarkus (Part 3)
  • Decoding eBPF Observability: How eBPF Transforms Observability as We Know It
  • What to Pay Attention to as Automation Upends the Developer Experience

Another Singleton Implementation

How to implement the Singleton pattern in Java in five different ways.

Davide Lorenzo Marino user avatar by
Davide Lorenzo Marino
·
Dec. 10, 15 · Opinion
Like (9)
Save
Tweet
Share
11.96K Views

Join the DZone community and get the full member experience.

Join For Free

The Singleton pattern is one of the most well known patterns.

There are many possible implementations of that pattern. The most common are:

  • Eager implementation.

  • Lazy implementation with single nonsynchronized check of the instance variable (only for non multithread environment).

  • Lazy implementation with synchronization over the whole method getInstance.

  • Lazy implementation with double check of instance variable.

An uncommon implementation of the Singleton pattern is the implementation with the lazy initialization holder class idiom (also known as initialize on demand holder class idiom).

Here I propose a brief description of all the most common implementation before describing the lazy initialization holder class idiom.

Eager Implementation

All implementations have two commons aspects:

  • A private constructor.

  • A public static method getInstance to retrieve the unique instance of the Singleton class.

The eager implementation builds the unique instance of the Singleton when the class is loaded in memory.

public class Singleton {
  // Builds the instance variable once loaded the Singleton class
  private static Singleton instance = new Singleton();

  private Singleton() {
    // The private constructor body
  }

  public static Singleton getInstance() {
    // Returns the already build with an eager approach instance variable
    return instance;
  }
}

Lazy Implementation Not Synchronized

The lazy implementation not synchronized works only for non multithreaded environments.

public class Singleton {
  private static Singleton instance;

  private Singleton() {
  }

  public static Singleton getInstance() {
    // Here a single check not synchronized
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

Lazy Implementation With Whole Synchronization

Similar to the previous implementation but with a synchronized getInstance method that guarantees a correct use also in a multithread environment.

public class Singleton {
  private static Singleton instance;

  private Singleton() {
  }

  public static synchronized Singleton getInstance() {
    // Here a single check but in a synchronized getInstance method
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

Double Check 

The previous implementation is not the best one for multithread environment because the whole method getInstance has been synchronized.

In a multithread enviroment it is better to synchronize the smallest portion of code possible.

The double check implementation try to do exactly that.

public class Singleton {
  private volatile Singleton instance;

  private Singleton() {
  }

  public static Singleton getInstance() {
    // First check 
    if (instance == null) {
      synchronized(Singleton.class) {
        // Second check inside a synchronized block
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}

Lazy Initialization Holder Class Idiom

A class is not initialized before it is used. Knowing that it is possible to create a new elegant implementation of the Singleton pattern.

Instead of saving the instance variable in the Singleton class, we hide it in an inner class SingletonHolder.

We define the nested class SingletonHolder as static so it is possible to use it without instantiating the Singleton. The body of the SingletonHolder has only one static final member instance that is eager initialized to a new Singleton instance.

The getInstance method of Singleton simply returns the value of the instance variable held in the SingletonHolder nested class. 

Because the class SingletonHolder is called only when somebody calls the method getInstance of the Singleton, the Singleton instance is created lazily after the first demand. 

The internal implementation of the JVM guarantees that the initialization of the SingletonHolder class is done synchronously. After the initialization, no synchronization is needed because the instance variable can't be changed (it is final). So we have a lazy creation of the instance safe in a thread environment without any explicit synchronization block.

Here's the code:

public class Singleton {
    private Singleton() {
        // The body of private constructor
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }

    // Inner static class that holds a reference to the singleton
    private static class SingletonHolder {
        private static final Singleton instance = new Singleton();
    }
}


Implementation

Opinions expressed by DZone contributors are their own.

Trending

  • DevOps in Legacy Systems
  • Microservices With Apache Camel and Quarkus (Part 3)
  • Decoding eBPF Observability: How eBPF Transforms Observability as We Know It
  • What to Pay Attention to as Automation Upends the Developer Experience

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: