javasingletondouble-checked-locking

Why to double check the singleton instantiation


In this link i found the singleton instantiation as below:

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

I am not getting the point of single check ie (1) . Whats its use here any way the single thread will be checking the instance inside synchronized block , so what is point of using the first check?


Solution

  • Consider that in a multithreaded environment two threads can access your singleton. Here is what can happen without a double check.

    First thread enters getInstanceDC(); _instance is null so it enters the if block. Second thread enters getInstanceDC(); _instance is null so it enters the if block. First thread creates a new instance. Second thread creates a new instance.

    The double check in a synchronized block solves this problem.

    So why not synchronize the whole method? The answer is for performance reasons.