Friday, July 4, 2008

Singleton In Different Way

public class Singleton {
    private Singleton() {
    private static class SingletonHolder {
        private static final Singleton singleton = new Singleton();
    public static Singleton getInstance() {
        return SingletonHolder.singleton;
Whenever a class is first loaded by JVM it's static variable and static initialiser bloacks are executed. In the above example when the class Singleton is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables and initializer blocks, the initialization completes simply. The JVM will not load the static class definition SingletonHolder within Singleton class until you touch something in the SingletonHolder class. Hence the static variable is not initialized until the JVM determines that SingletonHolder must be loaded or executed. The static class SingletonHolder is only executed when the static method getInstance is invoked on the class Singleton.
The first time when this class will be loaded by the JVM the static variable singleton will be initialized by executing the (private) constructor for the outer class Singleton. As per the Java Language Specification (JLS) the class initialization phase is guaranteed to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization. As the initialization phase initializes the static variable singleton in synchronized manner, all subsequent concurrent invocations of the getInstance will return the same correctly initialized singleton without incurring any additional synchronization overhead.

No comments:

Post a Comment