Describe Thread safe Lazy Singleton Implementation

The easier way to create a thread-safe singleton class is to make the global access getInstance() method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.

public class Singleton {
    
    private static Singleton instance;
    
    /* Private constructor to prevent instantiation by external classes */
    private Singleton (){}
    
    /**
     * synchronized method thus only one thread can create the instance.
     * From the next thread the null check will fails thus the instantiation
     * code will be executed only once
     */
    
    public static synchronized Singleton getInstance(){
        if(instance == null){
            instance = new Singleton ();
        }
        return instance;
    }
} 

Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method. To avoid this extra overhead every time, the following implementation will uses a synchronized block instead of synchronized method.

public class Singleton {

    private static Singleton instance;

    /**
     * Private constructor to prevent instantiation by external classes
     */
    private Singleton() {
    }

    /**
     * Here we are using a synchronized block with double lock to ensure
     * thread safety. But check the lock is acquired on the class Object
     * associated with Singleton class.
     */
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

CORE JAVA CREATIONAL-PATTERN