Technical Interview Questions

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

Archive for the ‘Design Patterns’ Category

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 
  { 
    private: 
    static Singleton instance; 

    protected Singleton() 
    { 
    } 

    public static Singleton CreateInstance() 
    { 

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

Advertisements

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

Singleton Pattern: Part 1 Trivial implemenation

Posted by tekpool on October 19, 2006

Singleton Pattern: Part 1 Trivial implemenation

The purpose of a singleton pattern is to ensure a unique instance of the class and to provide global access to this. It falls under the Creational patterns category.

The class implementing the singleton pattern will have to do the following items:

  1. Provide an Instance Creation Method to the user.
  2. Maintain the unique instance throughout the life of the program(s) in which this class is created.

To maintain the unique instance, the class will have to remove the normal object creation procedure away from the user. The normal object creation is through the constructor. Taking this away from the user would mean, making the constructor as private or protected. With the absence of a public constructor, the class now can take total control on how its instances are created. The only way to do this, is to provide a static method (say CreateInstance). Why static? Because, the user can actually call this method without creating an object (which is obviously out of the user’s control).

The logic of the CreateInstance method is pretty straightforward. Check, if any instance has already been created, if yes, return the instance, else create and store the instance and return it. It is obvious here again, storing the instance has to be done in a private static variable, static because, you are doing this in a static method, private because, you need to do the maintenance of the singleton instance creation.

Here’s the code sample to demonstrate this. I am going to promote Test Driven Development in my examples.

The TestApp::TestSingleton() method is the test code that I wrote even before writing the actual Singleton class. I will discuss Test Driven Development in detail in another series.

  class TestApp 
  { 
    public: 
    static void TestSingleton() 
    { 

      Singleton s1 = Singleton.Instance(); 
      Singleton s2 = Singleton.Instance(); 

      if (s1 == s2) 
      { 
        printf("PASSED:  
        Objects are of the same instance"); 
      } 
      else 
      { 
        printf("FAILED:  
       Objects do not point to the same instance"); 
      } 

    } 
  } 

// WARNING: DO NOT USE THIS CODE ANYWHERE. 
// THIS IS A VERY TRIVIAL IMPLEMENATION. WE WILL 
// DISCUSS THE ISSUES WITH THIS IN FUTURE POSTS. 

  class Singleton 
  { 
    private: 
    static Singleton instance; 

    protected Singleton() 
    { 
    } 

    public static Singleton CreateInstance() 
    { 

      if (instance == null) 
      { 
        instance = new Singleton(); 
      } 

      return instance; 
    } 
  } 
}

Posted in C++, Design Patterns, General, Microsoft, Progamming Languages | 1 Comment »