Our general approach to the Singleton Class design is very simple and we hardly think of the thread safe condition. But recently I got one question from my peers about how to implement the Threadsafe Singleton implementation.

It was very much valid question and also quite interesting and today will just share my approach with respect to the threadsafe Singleton implementation.

Normal Approach to Singleton Class :

public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}
 

Above code works perfectly in the environment in which at a time only one thread access the class. But in Multi-thread environment it will fail.

So for Multi-thread environment we tweaked a code little for which we got idea from the below link where they have explained the pros and cons of the below approach and also on which environment it will fail.

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

Above code is also not full proof and it won’t work for a particular condition. For more details you can refer to the above link where they have explained briefly of its pros and cons. Please do comment if you have any other suggestion and any other approach which is full proof.

Share

Related Posts:

  • No Related Posts