Can any one explain how below code would work fine in multithreaded environment especially when it is not using synchronized keyword?
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Unsynchronised singletons can work just fine in threaded environments provided they’re instantiated in one thread before other threads attempt to use them.
This may be as simple as calling
getInstance()from the main thread before starting up any of those other threads.However, that’s irrelevant in this particular case. Since your instance variable is
static final, this means it will be constructed when the class is initially loaded. By callinggetInstance(), the classloaders brings in the class and, as part of that, constructs theINSTANCEmember before allowing the call through togetInstance()to proceed.The classloader itself has locking mechanisms to prevent concurrent execution by multiple threads and therefore all calls to
getInstance()(including the first, immediately following the loading of the class) will return the already-initialised value.