How below 2 codes are different in terms of multithreaded environment?
Code 1:
public class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } Code 2:
class Singleton { private static Singleton uniqueInstance; private Singleton() { ... } public static Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } } Why Code 2 will not work in multi threaded environment, when it has also static variable declared which will get loaded once class is loaded & thus it'll have only one instance?
Thanks!