Thread Safety Singleton

If you are new to design pattern please read my blog on Design Pattern then read about Singleton Design Pattern.
So let’s continue about Thread Safety Singleton.
There are various ways to implement Singleton Design Pattern.

  • No Thread Safe
  • Thread Safety
  • Thread Safety using Double Check Locking
  • Lazy Instantiation

I will write about Thread Safety Singleton here, No thread Safe singleton already covered in my previous blog.

Below is the code to implement No Thread Safe Singleton.

private static Singleton objSingleton = null;
        public static Singleton GetObject
        {
            get
            {
                if (objSingleton == null)
                    objSingleton = new Singleton();
                return objSingleton;
            }
        }

Thread Safety Singleton

In Thread, Safe Singleton thread gets a lock and then checked for instance created or not. This implementation ensures only one thread will create an object of the class.
        private static Singleton objSingleton = null;
        private readonly static object padlock = new object();
        public static Singleton GetObject
        {
            get
            {
                lock (padlock)
                {
                    if (objSingleton == null)
                        objSingleton = new Singleton();
                    return objSingleton;
                }
            }

Leave a Comment

RSS
YouTube
YouTube
Instagram