Lazy Initialization Thread Safe & Auto Thread Safe for Singleton Pattern

We all know what Singleton Pattern is, one Class can’t allow more than one instance created. Now, we start from simple Singleton pattern implementation, then find different ways of making thread safe singleton class.

First, basic Singleton Pattern

  
/**
 * Basic Singleton pattern implementation with no thread safety, buy privatizing default constructor
 */
class Singleton{
    private static Singleton instance = null;

    private Singleton() {}

    public static Singleton getSingleInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

Second, thread safe Singleton pattern using lazing initialization and synchronized

  
/**
 * Lazy Initialization + ThreadSafe with synchronized keyword
 */
class ThreadSafeSingleton{
    private static ThreadSafeSingleton instance = null;

    private ThreadSafeSingleton() {}

    public static synchronized ThreadSafeSingleton getThreadSafeSingletonInstance(){
        if(instance == null){
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
}

Third, thread safe Singleton instance created during class loading, and the benefit is skipping checking instance==null

 
class AutoTsSingleton{
    private static final AutoTsSingleton instance = new AutoTsSingleton();

    private AutoTsSingleton(){}

    public static AutoTsSingleton getInstance(){
        return instance;
    }
}

Leave a Reply