Ragunath Jawahar Ragunath Jawahar - 1 month ago 22
Java Question

Singleton pattern

The following snippet is straight forward,

public MyClass getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new MyClass();
}
return uniqueInstance;
}


What does the following one do?

public MyClass getInstance() {
if(uniqueInstance == null) {
synchronized(MyClass.class) {
uniqueInstance = new MyClass();
}
}
return uniqueInstance;
}

Answer

It's a poor attempt to make it threadsafe to prevent a race condition caused by at least two threads which have simultaneously entered the if block.

A bit more safe approach is adding an extra nullcheck, also known as double-checked locking.

public MyClass getInstance() {
    if (uniqueInstance == null) {
        synchronized(MyClass.class) {
            if (uniqueInstance == null) {
                uniqueInstance = new MyClass();
            }
        }
    }
    return uniqueInstance;
}

However, I usually prefer Just Create One pattern over Singleton.