Make your singleton class thread safe

In this post, we try to get an idea about making thread-safe singleton.

A singleton is a class which only allows a single instance of itself to be created. This class usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance. Now, in order to make singleton class thread-safe, we can apply to the double-check locking algorithm. In this algorithm, we can put two if conditions to check object is null or not.
First, if condition checks if the object is not null then return the already created object. The second condition we put inside the lock to check if the object is null then only create a new object. The benefit of putting inside condition is to check if multiple threads bypass the first condition at the same time and waiting for their turn to take the lock. Then, in this case, both threads will create a new object. For stopping the above issue, we have to put the second condition.
Below is the example of double-checking locking.
 public class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton singleton = null;
        private Singleton() { }
        public static Singleton GetSingleton()
        {
            //check 1
            if (singleton != null)
                return singleton; Monitor.Enter(s_lock);
            //check 2
            if (singleton == null)
            {
                Singleton temp = new Singleton();
            }
            Monitor.Exit(s_lock);
            return singleton;
        }
    }

Advertisements