Double-checked Locking
Lets us have a look of Singleton pattern, In Singleton pattern we used some type of synchronization in java, so that only only one thread can access that synchronized method or block. Lets have a look of singleton class.
public class SingletonClaz { // Constructor class private SingletonClaz() { } // Single class Instance private static SingletonClaz singletonInstance; // synchronized method public static synchronized SingletonClaz getInstance() { if (singletonInstance == null) { singletonInstance = new SingletonClaz(); } return singletonInstance;// Returning an instance } }
In the above code you can see that only one thread can access the synchronized method. i.e. If one thread is executing the synchronized method the other will simply returned with the null singleton instance without getting the instance of the SingletonClaz. So the only one thread gets the instance of the synchronized method.
Therefore we can make this method more efficient as,
// Single class Instance private static SingletonClaz singletonInstance; // synchronized method public static SingletonClaz getInstance() { if (singletonInstance == null) { // Making Synchronized Block synchronized (SingletonClaz.class) { singletonInstance = new SingletonClaz(); } } return singletonInstance;// Returning an instance }
In the above code you can see that when one thread enters into the synchronized block the other thread waits (blocked). When first exits the other enters into the synchronized block. But when the other thread enters into the synchronized block get create an instance, remember it is not checked at that time. Therefore we prefer Double-Checked locking.
In double checked locking we do something like this
public class SingletonClaz { // Constructor class private SingletonClaz() { } // Single class Instance private static SingletonClaz singletonInstance; // synchronized method public static SingletonClaz getInstance() { if (singletonInstance == null) { // Making Synchronized Block synchronized (SingletonClaz.class) { if (singletonInstance == null) { singletonInstance = new SingletonClaz(); } } } return singletonInstance;// Returning an instance } }
Therefore the reason behind that the second check prohibits those thread who had already got an instance of SingletonClaz.