Singleton Pattern – Thread Safety Issues

multithreadingobject-orientedsingleton

Is the singleton pattern prone to thread safety problems? If so, what are the best methods to work around them?

Best Answer

It is heavily depend on the programming language specification & how thread safety is you implemented.

For example: code provided below uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs.

public class Singleton {
        private static volatile Singleton instance = null;

        private Singleton() {   }

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

Here is a referencing article on how to correctly implement thread safe Singleton Pattern in C#.

Related Topic