Thread safe Singleton in Java

1. Static field

public class Singleton {
    public static final Singleton INSTANCE = new Singleton(); 
} 

2. Enum

public enum Singleton {
    INSTANCE; 
} 

3. Synchronized Accessor

public class Singleton {
    private static Singleton instance;
    
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

4. Double Checked Locking & volatile

double checked locking Singleton is one way to create a thread-safe class that implements the Singleton pattern. This method tries to optimize performance by blocking only when the loner is instantiated for the first time.

public class Singleton {
        private static volatile Singleton instance;
    
        public static Singleton getInstance() {
        Singleton localInstance = instance;
        if (localInstance == null) {
            synchronized (Singleton.class) {
                localInstance = instance;
                if (localInstance == null) {
                    instance = localInstance = new Singleton();
                }
            }
        }
        return localInstance;
    }
}

Note that volatile is required. The Double Checked Lock problem lies in the Java memory model, more precisely in the order of object creation, when it is possible that another thread can receive and start using (based on the condition that the pointer is not null) an incompletely constructed object. Although this problem was partially addressed in JDK 1.5, the recommendation to use volatile for Double Checked Lock remains in place.

5. On Demand Holder Idiom

public class Singleton {
        
    public static class SingletonHolder {
        public static final Singleton HOLDER_INSTANCE = new Singleton();
    }
        
    public static Singleton getInstance() {
        return SingletonHolder.HOLDER_INSTANCE;
    }
}


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed