FIRST OFF: Yes, I know that the best way to make singles in Java is with enums, but if for some reason you need to subclass a singleton class, you cannot use enumerations, so ...
David Geary at JavaWorld has published an article long ago on introducing singletones in Java. He argued that the following optimization for the in-line implementation of a singleton solution is problematic:
public static Singleton getInstance()
{
if (singleton == null)
{
synchronized(Singleton.class)
{
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
(For more details see: http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=4#sthash.G8lzWOfT.dpuf )
Giri says this optimization with double lock verification
, - . , 1 , , singleton , Thread 2 singleton.
: ? Goetz Java concurrency, , , ... , singleton = temp; , , . , .
public static Singleton getInstance()
{
if (singleton == null)
{
synchronized(Singleton.class)
{
if(singleton == null) {
Singleton temp = new Singleton();
singleton = temp;
}
}
}
return singleton;
}