Design thread safe Singleton Class in C# Considering Performance

In, C# programming, Singleton in multi-threaded environment can produce more than one objects of singleton class if not designed properly. Where singleton class is expected to return only one of its instance. In this section, we will design the thread safe singleton class which was not designed in the answer of C# technical interview question i.e.  explain C# singleton class with example , which is recommended to read before continuing to thread safe singleton class design.

In multi-threaded environment, multiple threads can enter into GetInstance() method’s if condition when object is getting created first time. So, there is chance for more than one object creation. But, singleton class target is to create only one object.

So, we have to put lock in this block so only one thread can enter and create object.

public static SingleInstanceClass GetInstance()
        {                         
             if (instance == null)
             {
                //In multi threaded environment multiple threads can enter
                //here and may create more than one objects.
                 instance = new SingleInstanceClass();
              }               
                       

            return instance;
        }

Let’s put the lock to avoid multiple object creation. Below function design ensures for a single object creation.

public static SingleInstanceClass GetInstance()
        {            
                lock (mutex)
                {                   
                    if (instance == null)
                    {                     
                        instance = new SingleInstanceClass();
                    }
                }                      

            return instance;
        }

But, there is a performance issue now. Let’s say GetInstance() method is getting called again and again during program execution then every time it will check the lock making application slow.

To avoid performance issue, better solution is to put one more if condition to avoid calling locks.

Below piece of code will avoid lock performance issue with singleton thread safe double check concept.

public static SingleInstanceClass GetInstance()
        {
            
            if (instance == null)
            {               
                lock (mutex)
                {
                    //
                    if (instance == null)
                    {
                        //Create
                        instance = new SingleInstanceClass();
                    }
                }
            }           

            return instance;
        }

Thread Safe Singleton class example design – Complete C# Program Example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SingletonDesignPattern
{

    //Singleton class that returns only one object.
    public class SingleInstanceClass
    {
        //create a mutex object to lock shared statement in GetInstance
        //method
        private static readonly object mutex = new object();        
        private static SingleInstanceClass instance = null;
        
        private SingleInstanceClass()
        {
        }

        public static SingleInstanceClass GetInstance()
        {
            if (instance == null)
            {
                lock (mutex)
                {
                    if (instance == null)
                    {
                        instance = new SingleInstanceClass();
                    }
                }
            }

            return instance;
        }       

        public void Display(){
            Console.WriteLine("Singleton class");
        } 
    }

    //CLIENT CLODE

    class Program
    {
        static void Main(string[] args)
        {
            //Create 2 objects of the singleton class
            SingleInstanceClass obj1 = SingleInstanceClass.GetInstance();
            obj1.Display();
            SingleInstanceClass obj2 = SingleInstanceClass.GetInstance();
            obj2.Display();
        }
    }
}


Related Posts