double check locking in singleton pattern
c#
Solution
Jon Skeet explains this in detail.
Locks are expensive. If the object already exists, there's no point in taking out a lock. Thus, you have a first check outside the lock.
However, even if the object didn't exist before you took the look, another thread may have created it between the `if` condition and the `lock` statement. Therefore, you need to check again inside the lock.
However, the best way to write a singleton is to use a `static` constructor:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
Problem
it may be basic question to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locking in singleton pattern? And more what does double-checked locking means? ``` class singleton { private static singleton instance = null; private static singleton() { } private static object objectlock = new object(); public static singleton Instance { get { lock (objectlock) //single - check lock { if (instance == null) { instance = new singleton(); } return instance; } } } } ```