Note that a simple and thread-safe way to create a singleton is:
public class SimpleSingleton {
private SimpleSingleton() {}
private static SimpleSingleton instance = new SimpleSingleton();
public static SimpleSingleton getInstance() {
return instance;
}
}
The first reference to SimpleSingleton will initialize the static instance field, and the JVM will take care of synchronization if there is a race condition in invoking getInstance().
If early initialization of the singleton is not a performance concern (which is probably the majority of cases), then the above snippet suffices. However, there are scenarios under which the instance member variable may be initialized prior to invoking the getInstance() method, so if you are really concerned about only initializing if necessary, then a different approach is needed.
One route is to synchronize the getInstance method, but that creates overhead on each call.
An elegant solution is to create a private inner class as an initialization-on-demand holder:
public class SimpleSingleton { private SimpleSingleton() {}
private static class Holder { private static SimpleSingleton instance = new SimpleSingleton(); }
public static SimpleSingleton getInstance() { return Holder.instance; }}
The only reference to the Holder inner class occurs in the getInstance method, so it is guaranteed that initialization will only happen during the method's first invocation.
The holder pattern is simple and readable enough that I use it by default on all of my singleton implementations.