Singleton: Initialize-On-Demand Holder Class idiom
Memory model article and Initialize-On-Demand Holder Class idiom
Listing 2. The Initialize-On-Demand Holder Class idiom
This idiom derives its thread safety from the fact that operations that are part of class initialization, such as static initializers, are guaranteed to be visible to all threads that use that class, and its lazy initialization from the fact that the inner class is not loaded until some thread references one of its fields or methods.
Listing 2. The Initialize-On-Demand Holder Class idiom
private static class LazySomethingHolder {
public static Something something = new Something();
}
...
public static Something getInstance() {
return LazySomethingHolder.something;
}
This idiom derives its thread safety from the fact that operations that are part of class initialization, such as static initializers, are guaranteed to be visible to all threads that use that class, and its lazy initialization from the fact that the inner class is not loaded until some thread references one of its fields or methods.
Comments