Tuesday, December 23, 2014

Thread safe Singleton


Thread safe singleton :

public class LazyInitSingletonUsingHolder {

private static class InstanceHolder {
private static final LazyInitSingletonUsingHolder INSTANCE =
                          new LazyInitSingletonUsingHolder();
}

public static LazyInitSingletonUsingHolder getInstance() {
return InstanceHolder.INSTANCE;
}

private Object readResolve() {
return getInstance();
}
}


When the class 'LazyInitSingletonUsingHolder' is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class 'InstanceHolder' within it is not initialized until the JVM determines that 'InstanceHolder' must be executed. The static class 'InstanceHolder' is only executed when the static method getInstance() is invoked on the class LazyInitSingletonUsingHolder, and this is the first time JVM will load and initialize the 'InstanceHolder' class. Since the class initialization phase is guaranteed by the Java language specification to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance() method during loading and initialization. And since the initialization phase writes the static variable INSTANCE in a serial operation, all subsequent concurrent invocations of the getInstance() will return the same correctly initialized INSTANCE without incurring any additional synchronization overhead.

This gives a highly efficient thread-safe "singleton" without synchronization overhead.

No comments:

Post a Comment

Thanks for your comments/Suggestions.