I read this question about how to do Double-checked locking:
// Double-check idiom for lazy initialization of instance fields
private volatile FieldType fiel
Using Enum or nested static class helper for lazy initialization otherwise just use static initialization if the initialization won't take much cost (space or time).
public enum EnumSingleton {
/**
* using enum indeed avoid reflection intruding but also limit the ability of the instance;
*/
INSTANCE;
SingletonTypeEnum getType() {
return SingletonTypeEnum.ENUM;
}
}
/**
* Singleton:
* The JLS guarantees that a class is only loaded when it's used for the first time
* (making the singleton initialization lazy)
*
* Thread-safe:
* class loading is thread-safe (making the getInstance() method thread-safe as well)
*
*/
private static class SingletonHelper {
private static final LazyInitializedSingleton INSTANCE = new LazyInitializedSingleton();
}
The "Double-Checked Locking is Broken" Declaration
With this change, the Double-Checked Locking idiom can be made to work by declaring the helper field to be volatile. This does not work under JDK4 and earlier.
class Foo {
private volatile Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null)
helper = new Helper();
}
}
return helper;
}
}