Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton thread safe in C# - why to add the double check?

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

I don't understand why is the double check ! I read that this double check is to solve the thread concurrency problems - but ...

  1. The lock will solve it - so why we need to first 'if'

  2. if this singleton will be without the first 'if' it still will be thread safe - right ?

  3. if the first 'if' is false - so thread1 will init the 'instance' object => now, the 'instance' is not null and the thread1 is still in the lock block ===>> now, thread2 check the first 'if' and will get false => so he will not get to the 'lock' and imminently will return the instance and thread2 is able to change properties of the 'instance' => so thread1 && thread2 are 'working' on same 'instance' object => so where is the thread safe ... or what I'm missing here.

like image 986
Yanshof Avatar asked Feb 21 '23 13:02

Yanshof


2 Answers

1.The lock will solve it - so why we need to first 'if'

So you won't lock the thred unless you need to create the new instance of the Singleton.
lock is a very expensive operation, so it's worth doing that extra check.

2.if this singleton will be without the first 'if' it still will be thread safe - right ?

Yes, but significantly slower.

3.Thread1 && thread2 are 'working' on same 'instance' object => so where is the thread safe

This is the whole point of singleton, only one instance for all threads. That's the thread safe thing...

like image 170
gdoron is supporting Monica Avatar answered Feb 23 '23 03:02

gdoron is supporting Monica


I assume that if ThreadA gets interrupted just before the lock; ThreadB successfully completes the creation of the singleton then when ThreadA resumes it'll try to recreate the singleton once the lock is released.

like image 35
James Avatar answered Feb 23 '23 02:02

James