I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:
class Singleton{
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null) instance = new Singleton();
return instance;
}
}
Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)
Josh Bloch recommends using a single-element
enumtype to implement singletons (see Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type).Some people think this is a hack, since it doesn’t clearly convey intent, but it does work.
The following example is taken straight from the book.
Here is his closing arguments:
On
enumconstant singleton guaranteeJLS 8.9. Enums
On lazy initialization
The following snippet:
Produces the following output:
As you can see,
THE_ONEconstant is not instantiated through the constructor until the first time it’s accessed.