Singleton Pattern

Singleton Pattern


The Singleton Pattern ensures a class has only one instance, and provide a global point of access to it.

1.     Synchronize the getInstance() method


public class Singleton{

   private static Singleton uniqueInstance;
   
   private Singleton() { }              // private constructor

   public static synchronize Singleton getInstance() {

       if(uniqueInstance == null)

            uniqueInstance = new Singleton();

    return uniqueInstance;

}


}


But Synchronizing  a method can decrease performance by a factor of 100.


2. Move to eargerly created Instance rather than lazily created one. If performance is an issue in your use of getInstance() method then this method of implementing the Singleton can drastically reduce the overhead.

Using this approach, we rely on the JVM to create the unique instance of the Singleton when class is loaded.The JVM guarantees that the instance will be created before any thread accesses the static uniqueInstance variable.

      public class Singleton{

            private static Singleton uniqueInstance = new Singleton(); 

             private Singleton() {}

            public static Singleton getInstance() {

                       return uniqueInstance;

                 }

      }
  

3. Use "double - checked locking" to reduce the use of Synchronization in getInstance()

    With double -checked locking, we first check to see if an instance is created and if not THEN we synchronize.This way we only synchronize the first time through,just what we want..

Volatile keyword ensures that multiple threads handle the uniqueInstance variable correctly when it is being initialized to the Singleton instance.


     public class Singleton{

            private volatile static Singleton uniqueInstance ; 

             private Singleton() {}

            public static Singleton getInstance() {
  
                       if(uniqueInstance == null){

                        synchronized (Singleton.class) {

                         if( uniqueInstance == null) { 
                                          uniqueInstance = new Singleton();

                               }
                          }

                    }
                       return  uniqueInstance;

      }

}