Over a million developers have joined DZone.

Another Singleton Implementation

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

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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();
    }
}


Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
java ,singleton pattern ,lazy initialization ,design patterns ,singleton

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}