Singleton Design Pattern With Thread Safety

I will not give much theory details in the article, but I will try to emphasis on thread safety. But still in case the audience is not much experienced still they can read and understand the usage of Singleton pattern as well in detail.

About Singleton

It’s a software design pattern and allows class to have only once instance. It’s really helpful when the requirement is to restrict the instance/object creation.

Example: How actually we implement the Singleton design pattern without thread safety.

  1. public sealed class WithOutThreadSafe  
  2. {  
  3.     private static WithOutThreadSafe _objWithOutThreadSafe = null;  
  4.     private WithOutThreadSafe()  
  5.     {}  
  6.     public static WithOutThreadSafe GetInstance()  
  7.     {  
  8.         if(_objWithOutThreadSafe == null//Incase object is null we have to create a new instance   
  9.         //This way is not thread safe as in case two thread encountered in the same condition then two instance can be created.  
  10.         {  
  11.             _objWithOutThreadSafe = new WithOutThreadSafe();  
  12.         }  
  13.         return _objWithOutThreadSafe;  
  14.     }  
  15. }  
You are right, there is nothing new about this code, actually this is the way of implementing Singleton design pattern.

But if you will check the code you can find the above written code is not type safe. Two threads may lead in that condition if (_objWithOutThreadSafe == null) and then we might have two instances.

Now look at the following code which is type safe:
  1. public sealed class WithThreadSafe  
  2. {  
  3.     private static WithThreadSafe _objWithThreadSafe = null;  
  4.     private static readonly object _objLock = new object();  
  5.     private WithThreadSafe()  
  6.     {}  
  7.     public static WithThreadSafe GetInstanceInstance()  
  8.     {  
  9.         lock(_objLock) //Here until lock is being removed second instance cant be created  
  10.             {  
  11.                 if(_objWithThreadSafe == null)  
  12.                 {  
  13.                     _objWithThreadSafe = new WithThreadSafe();  
  14.                 }  
  15.                 return _objWithThreadSafe;  
  16.             }  
  17.     }  
  18. }  
This implementation is Thread Safe. There will be a lock on the shared object and takes care of the issue.

We can have one more approach by merging both the approaches as in the following code snippet,
  1. if(_objWithThreadSafe == null)  
  2. {  
  3.     lock(_objLock)  
  4.     {  
  5.         if(_objWithThreadSafe == null)  
  6.         {  
  7.             _objWithThreadSafe = new WithThreadSafe();  
  8.         }  
  9.     }  
  10. }  
  11. return _objWithThreadSafe;  
Also, you can have thread safety without using lock. There are many ways to achieve the same. My aim is to show the thread safety concept.