Technical Interview Questions

The largest pool of technical questions with answers, explantions, code and detailed analysis

Archive for October 27th, 2006

Singleton Pattern: Part 2 Thread-Safe implemenation

Posted by tekpool on October 27, 2006

Singleton Pattern: Part 2 Thread-Safe implemenation

We looked into a trivial implementation of the singleton pattern in the previous post. The implementation was both lazy and non-thread safe. It’s lazy, because the singleton instance is created only when it’s required. The implementation was also not thread safe. So, if several calls were made into this method from a multi-threaded program, you could end up creating multiple instances of the class, and also mess up seriously since the system expects to have only one instance.

The problem is at the place, where you check if the instance is null. This is how it could go all wrong. In a multithread environment, lets say 2 threads T1 and T2 are calling the CreateInstance() function. T1 executes the ‘if’ condition and then loses its time-slice, Meanwhile T2 gets its chance to execute code. At this point the singleton instance is not yet created. T2 then creates the object and returns the caller an instance of the newly created object. When T1 gets back another time-slice, it creates another object and returns that instance to its caller. Since it’s a static instance, T2 will lose it’s the state of the object it acquired and then hell breaks loose.

  class Singleton 
    static Singleton instance; 

    protected Singleton() 

    public static Singleton CreateInstance() 

      // Use a mutex locking mechanism 
      //  that suits your system 
      if (instance == null) 
        instance = new Singleton(); 
      return instance; 

Posted in C++, Design Patterns, General, Microsoft, Progamming Languages | 218 Comments »