scott miles scott miles - 1 month ago 7
Java Question

Why double lock is required for true singleton?

I see below implementation(Double-checked locking) to implement singleton class

public static Singleton getInstance() {
if(singleton == null) {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}


I am not getting what is the issue if i remove first if below i.e.
if(singleton == null)
. Below is the implementation which i find
threadsafe and simple without double lock. What is the issue in below code that i need double lock ?

public static Singleton getInstance() {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}

Answer

It's an optimization to avoid synchronization if the singleton has already been initialized.

It's also an old way of creating singletons in Java, since the enum mechanism provides a simpler way to get the same effect.

Comments