This is mainly a question of the degree of laziness. He is lazy in that he will not create a singleton until the class is initialized, but he longs for some situations when you want to use the class without initializing the singlet itself.
For instance:
public final class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } public static void sayHello() { System.out.println("Hello!"); } }
Calling Singleton.sayHello() will instantiate a singleton, even if we don't want it ... so it's not as lazy as it could be.
You can get around this with a nested type:
public final class Singleton { private Singleton() {} public static Singleton getInstance() { return Holder.instance; } public static void sayHello() { System.out.println("Hello!"); } private static class Holder { private static final Singleton instance = new Singleton(); } }
Now Singleton.Holder will only be initialized using the getInstance method. It is lazy and without thread without locking.
In my experience, usually the static singleton class method is the getInstance method, in which case they are equivalent (unless you use reflection to initialize the type in some way, for example).
source share