Singleton Class in Java

A singleton is simply a class that is instantiated exactly once in the Java Virtual Machine. It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects. The intention is to create a single instance of a object of classes which are expensive to create during runtime and try to reuse the same object. Such objects are mainly immutable.

Some basics rules required to implement a singleton class

  • Constructor should be private
  • Declare a static variable object of the class
  • Declare a static method to return the instance

There are multiple variations to implement singleton class.

  • Early initialization of class variable
     public class Singleton {
      private final static Singleton obj = new Singleton() ; //early init
      private Singleton () {}; //private constructor
      public static Singleton getInstance() {
        return obj;
      }
    }
  • Lazy initialization of class variable
     public class Singleton {
      private final static Singleton obj = null ;
      private Singleton () {}; //private constructor
      public static Singleton getInstance() {
        if (null == obj) {
          obj = new Singleton();
        }
        return obj;
      }
    }
    The above code look resonably correct. It may fail in multithreaded environment, where Thread1 see that obj is null and enters the if loop to create obj and at the same time Thread2 also comes and find obj as null and enters the loop and create another object. This would result in having multiple instances of singleton class. This problem can be solved by Double Locking.
  • Making above code thread safe by double locking.
  •  public class Singleton {
    private final static Singleton obj = null ;
      private Singleton () {}; //private constructor
      public static Singleton getInstance() {
        if (null == obj) {
          synchronized(Singleton.class) {
            if (null == obj) {
                obj = new Singleton();
            }
          }      
        }
        return obj;
      }
    }
    Lets see what happening in above code. In the above code snippet imagine that multiple threads comes concurrently and tries to create the new instance. In such situation there may be three or more threads are waiting on the synchronized block to get access. Since we have used synchronized only one thread will be given access. All the remaining threads which were waiting on the synchronized block will be given access when first thread exits this block. However when the remaining concurrent thread enters the synchronized block they are prevented to enter further due to the double check : null check. Since the first thread has already created an instance no other thread will enter this loop.
  • With JDK 1.5 enum (preferred approach). Since Enum is thread safe, its become simplest to implement.
     public enum Singleton {
     INSTANCE;
    }
    
  • More Interesting Reads