Saturday 19 September 2015

Singleton Design Pattern using Double Checked Locking Idiom

Singleton design pattern using Double checked locking pattern
In my last interview, I was asked to write code to implement Singleton design pattern using "Double checked locking" idiom, which I thought to share with you all. In Singleton design pattern, only instance of class is created during application lifetime and that's shared between all its clients. One of the challenge with Singleton pattern is to ensure that only instance of class is created without compromising performance.


In simplest, Singleton pattern implementation, the getInstance() method, which is used to retrieve Singleton instance was made static synchronized as shown below :

 public synchronized static JavaSingleton getInstance() {
        if (_instance == null) {
            _instance = new JavaSingleton();
        }
        return _instance;
    }

This code works fine because it guarantees that only instance of Singleton is gets created but it has severe performance overhead. When multiple thread will call getInstance(), they will block because its statically synchronized, even though none of them are creating singleton, they are just accessing existing instance.

If you look carefully, you will find that synchronization is only required, when creating Singleton instance, after that you don't need any synchronization. Double checked locking idiom solves this problem.

In Double checked locking, instead of making whole getInstance() method synchronize, only the critical section (which creates Singleton instance) is synchronized, to do that, _instnace variable is checked twice, one without locking and other with locking, hence this idiom is called "Double checked locking".

Here is sample code in Java to create thread-safe Singleton using Double checked locking pattern :

/**
 * Java Program to implement Singleton Patter using Double checked locking idiom
 */
public class JavaSingleton {

    private static volatile JavaSingleton _instance;

    /**
     * Double checked locking code on Singleton
     * @return JavaSingleton instance
     */
    public static JavaSingleton getInstance() {
        if (_instance == null) {
            synchronized (JavaSingleton.class) {
                if (_instance == null) {
                    _instance = new JavaSingleton();
                }
            }
        }
        return _instance;
    }

}


One of the most important thing to remember about this idiom is making _instnace volatile.  This idiom was broken before Java 5 because other thread could see the un-initialized instance and hence able to break the locking, but from Java 5 onward Java Memory Model provide happens before guarantee which means other thread will not see half-initialized result.

No comments:

Post a Comment