Initialization on demand holder idiom
Traditional simple way
Java 5 solution
The Enum-way
public
class
Singleton
{
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE , not before.
*/
private static class SingletonHolder {
private final static Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE , not before.
*/
private static class SingletonHolder {
private final static Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Traditional simple way
public
class
Singleton
{
public final static Singleton INSTANCE = new Singleton();
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected Singleton() {}
}
public final static Singleton INSTANCE = new Singleton();
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected Singleton() {}
}
Java 5 solution
public
class
Singleton
{
private static volatile Singleton INSTANCE;
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected Singleton() {}
public static Singleton getInstance() {
if (INSTANCE == null ) {
synchronized (Singleton. class ) {
if (INSTANCE == null )
INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}
The "Double-Checked Locking is Broken" Declaration.
private static volatile Singleton INSTANCE;
// Protected constructor is sufficient to suppress unauthorized calls to the constructor
protected Singleton() {}
public static Singleton getInstance() {
if (INSTANCE == null ) {
synchronized (Singleton. class ) {
if (INSTANCE == null )
INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}
The Enum-way
public
enum
Singleton
{
INSTANCE;
}
INSTANCE;
}