C# Singleton Design Pattern Example: Part 2

In this article we will see how to make it Thread Safe.

In my previous article, you might have seen the basic example of the Singleton Pattern in C# that was not thread safe. In this article, we will see how to make it thread safe.

Thread Safe Singleton class using early binding

  1. namespace PrashantBlogs.SingletonPattern  
  2. {  
  3.    /// <summary>  
  4.    /// The Singleton class that allows unique   
  5.    /// instance creation  
  6.    /// </summary>  
  7.    sealed class Singleton  
  8.    {  
  9.       //This is known as early binding or initialization  
  10.       private static Singleton _instance = new Singleton();  
  11.   
  12.       //Constructor is marked as private   
  13.       //so that the instance cannot be created   
  14.       //from outside of the class  
  15.       private Singleton()  
  16.       {  
  17.       }  
  18.   
  19.       //Static method which allows the instance creation  
  20.       static internal Singleton Instance()  
  21.       {  
  22.          //All you need to do it is just return the  
  23.          //already initialized which is thread safe  
  24.          return _instance;  
  25.       }  
  26.    }  
  27. }  
The preceding class has a static method that returns the instance of the Singleton class that is already initialized during its declaration as in the following.
  1. private static Singleton _instance = new Singleton();  
It ensures that the instance of the Singleton class is already created and the static method is an instance that just returns it whenever a call to this method is made by the calling applications.

Thread Safe Singleton class using lock
  1. using System;  
  2. namespace PrashantBlogs.SingletonPattern  
  3. {  
  4.    sealed class Singleton  
  5.    {  
  6.       private static readonly object _lockObj = new object();  
  7.       private static Singleton _instance = null;  
  8.       private Singleton()  
  9.       {  
  10.       }  
  11.       static internal Singleton Instance()  
  12.       {  
  13.          lock (_lockObj)  
  14.          {  
  15.             if (_instance == null)  
  16.             {  
  17.                _instance = new Singleton();  
  18.                Console.WriteLine("Created the instance of Singleton class");  
  19.             }  
  20.             else  
  21.             {  
  22.                Console.WriteLine("Returning already created instance of Singleton class");  
  23.             }  
  24.             return _instance;  
  25.          }  
  26.       }  
  27.    }  
The preceding class shows how the thread-safe singleton pattern can be implemented using the lock. The following line helps us to create an object that is used further to lock a critical section.
  1. private static readonly object _lockObj = new object();  
We have declared the Singleton instance variable in such a way that it can be initialized lazily when we actually request the instance of the Singleton class.
  1. private static Singleton _instance = null;  
The lock block forms a critical section to ensure that only one thread can enter it at a time and other threads must wait until the already entered thread comes out of this section so it's completely thread safe. The first thread will create the instance of the Singleton class and all other threads will share the same instance. However, if you observe it carefully, a lock is acquired every time the instance is requested that will hit the performance.

Thread Safe Singleton class using double-check locking
  1. using System;  
  2. namespace PrashantBlogs.SingletonPattern  
  3. {  
  4.    sealed class Singleton  
  5.    {  
  6.       private static readonly object _lockObj = new object();  
  7.       private static volatile Singleton _instance;  
  8.       private Singleton()  
  9.       {  
  10.       }  
  11.       static internal Singleton Instance()  
  12.       {  
  13.          if (_instance == null)  
  14.          {  
  15.             lock(_lockObj)  
  16.             {  
  17.                if(_instance == null)  
  18.                {  
  19.                   _instance = new Singleton();  
  20.                   Console.WriteLine("Created the instance of Singleton class");  
  21.                }  
  22.                else  
  23.                {  
  24.                   Console.WriteLine("Returning already created instance of Singleton class");  
  25.                }  
  26.             }  
  27.          }  
  28.          return _instance;  
  29.       }  
  30.    }  
  31. }  
The preceding Singleton class implements thread safety without the necessity of taking out a lock every time. It also solves the concurrency problems. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires such type of implementation. As in most cases, a static initialization approach is sufficient.

To test the preceding classes, you can use the following code snippet that is a main program written for creating a single instance using the Singleton Pattern.

Program.cs
  1. using System;  
  2. namespace PrashantBlogs.SingletonPattern  
  3. {  
  4.    class Program  
  5.    {  
  6.       static void Main(string[] args)  
  7.       {  
  8.          Console.WriteLine("Attempting to get the Singleton class instance");  
  9.          Console.WriteLine("The instance name is obj1");  
  10.          Singleton obj1 = Singleton.Instance();  
  11.          Console.WriteLine();  
  12.          Console.WriteLine("This is the second attempt to get the Singleton instance");  
  13.          Console.WriteLine("The instance name is obj2");  
  14.          Singleton obj2 = Singleton.Instance();  
  15.          Console.WriteLine();  
  16.          Console.WriteLine("This is the third attempt to get the Singleton instance");  
  17.          Console.WriteLine("The instance name is obj3");  
  18.          Singleton obj3 = Singleton.Instance();  
  19.          Console.WriteLine();  
  20.          Console.WriteLine("Comparing the three instances, obj1 == obj2 == obj3");  
  21.          if (obj1 == obj2 && obj1 == obj3 && obj2 == obj3)  
  22.          {  
  23.             Console.WriteLine("obj1, obj2 and obj3 are sharing the same instance");  
  24.          }  
  25.          Console.ReadKey();  
  26.       }  
  27.    }  
  28. }  
Output



Your feedback will help me in further improvements context wise so please feel free to post it/them.