Is this correct:
- Using a singleton with a holder gives lazy initialisation because the class
SingletonHolder
is only initialised whenSingleton.getInstance()
is run. This relies onSingletonHolder
only ever being referenced insideSingleton.getInstance()
. It's thread safe because the class loader takes care of synchronisation. - Using a singleton without the holder is eager initialisation because as soon as Java comes across code that references
Singleton
, all its static fields are resolved. It's also thread safe because the class loader takes care of synchronisation.
Singleton with a holder.
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private Singleton(){ }
}
Singleton without a holder.
public class Singleton{
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance(){
return INSTANCE;
}
private Singleton(){ }
}
Update in response to @jan's suggestion that this is a duplicate of What is an efficient way to implement a singleton pattern in Java?. I disagree. I am not asking what is the best way to do it: I am only asking what makes these two specific implementations lazy vs eager loading. Answers like xyz's broadly address lazy vs eager, but not by contrasting the two examples I was trying to examine (or with the same keywords which is why it never came up in my initial searches).