Lazy thread-safe Singleton using Double Checked Locking

suggest change

This thread-safe version of a singleton was necessary in the early versions of .NET where static initialization was not guaranteed to be thread-safe. In more modern versions of the framework a statically initialized singleton is usually preferred because it is very easy to make implementation mistakes in the following pattern.

public sealed class ThreadSafeSingleton
{
   private static volatile ThreadSafeSingleton instance;
   private static object lockObject = new Object();

   private ThreadSafeSingleton()
   {
   }

   public static ThreadSafeSingleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (lockObject) 
            {
               if (instance == null)
               {
                  instance = new ThreadSafeSingleton();
               }
            }
         }

         return instance;
      }
   }
}

Notice that the if (instance == null) check is done twice: once before the lock is acquired, and once afterwards. This implementation would still be thread-safe even without the first null check. However, that would mean that a lock would be acquired every time the instance is requested, and that would cause performance to suffer. The first null check is added so that the lock is not acquired unless it’s necessary. The second null check makes sure that only the first thread to acquire the lock then creates the instance. The other threads will find the instance to be populated and skip ahead.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Singleton Implementation:
* Lazy thread-safe Singleton using Double Checked Locking

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
42 Singleton Implementation
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script