Open In App

Java Program to Demonstrate the Double-Check Locking For Singleton Class

One of the key challenges faced by junior developers is the way to keep Singleton class as Singleton i.e. the way to prevent multiple instances of Singleton class. Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle. In double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to make sure that only one instance of singleton gets created.

Need of Double-checked Locking of Singleton Class:






private static Singleton instance;
  
public static Singleton getInstance1()
{
    if (instance == null) {
        instance = new Singleton();
    }
    return instance;
}

This brings us to double checked locking pattern, where only a critical section of code is locked. 

Why is it called Double Checked Locking?



How Double Checked Locking looks like in Java:




public static Singleton getInstance2()
{   // Single Checked
    if (instance == null) { 
        
        synchronized (Singleton.class)
        
            // Double checked
            if (instance == null) { 
                instance = new Singleton();
            }
        }
    }
    return instance;
}

Implementation double-checked locking on Singleton class:




// Java Program to write double checked locking 
// of Singleton class
  
class Singleton {
    private volatile static Singleton instance;
  
    private Singleton() {}
  
    // 1st version: creates multiple instances if two thread
    // access this method simultaneously
    public static Singleton getInstance1()
    {
        if (instance == null) {
            instance = new Singleton();
        }
  
        return instance;
    }
  
    // 2nd version : this is thread-safe and only
    // creates one instance of Singleton on concurrent
    // environment but it is unnecessarily expensive due to
    // cost of synchronization at every call.
    public static synchronized Singleton getInstance2()
    {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
  
    // 3rd version : An implementation of double checked
    // locking of Singleton. Intention is to reduce cost
    // of synchronization and improve performance, by only
    // locking critical section of code, the code which
    // creates instance of Singleton class.
    public static Singleton getInstance3()
    {
        if (instance == null) {
            synchronized (Singleton.class)
            {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


Article Tags :