Singleton thread safe in C# - why to add the double check?
c#, design-patterns, locking, singleton, thread-safety
Solution
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...
Problem
``` 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 ... The lock will solve it - so why we need to first 'if' if this singleton will be without the first 'if' it still will be thread safe - right ? 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.