32014Sep

Singleton In Java

Singleton in java is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it.

There are many ways to create singleton in java. These are : –

Singleton With Lazy Loading
public class SingletonLazy{

private static SingletonLazy instance; 

public static SingletonLazy getInstance(){
   if(instance == null){  
         instance = new SingletonLazy();
   }
   return instance;
}

private SingletonLazy();

}

Here instance of singleton class is created when we call getInstance(). That is why it is Lazy loading.

Singleton With Lazy Loading And Thread Safe
public class SingletonLazyThreadSafe{

private static volatile SingletonLazyThreadSafe instance; //volatile variable 

public static SingletonLazyThreadSafe getInstance(){

   if(instance == null){
            synchronized(SingletonLazyThreadSafe.class){
              if(instance == null)
              instance = new SingletonLazyThreadSafe();
            }

   }
   return instance;

}

private SingletonLazyThreadSafe(){}

}

Source – www.javarevisited.blogspot.in

If we do not make instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of instance as not null and they will believe its still null.

Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.

Singleton With Early Loading
public class SingletonEarly{

    //initailzed during class loading
    private static final SingletonEarly INSTANCE = new SingletonEarly();
  
    //to prevent creating another instance of Singleton
    private SingletonEarly(){}

    public static SingletonEarly getSingleton(){
        return INSTANCE;
    }
}

Since Singleton instance is static and final variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.

Things To Consider
  • Constructor must be private.
  • Instance variable must be static and volatile(for thread safe).
  • Method must be static which is returning object.