There is such a singleton implementation based on double checked locking ( item 2 ):
public class Singleton { private static volatile Singleton instance; public static Singleton getInstance() { Singleton localInstance = instance; if (localInstance == null) { synchronized (Singleton.class) { localInstance = instance; if (localInstance == null) { instance = localInstance = new Singleton(); } } } return localInstance; } } Question 1: What is localInstance used localInstance ? Why not do this:
public class Singleton { private static volatile Singleton instance; public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } ?
I have an assumption: reading a volatile field is a bit more expensive than reading a regular field or a local variable, which is why a local variable is used here. If I am right and someone can paint this moment in more detail - I would be grateful.
Question 2: Why is a private constructor not declared in this class? Indeed, in the absence of it somewhere in the code, you can explicitly create an instance of this class.