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; } } } }
Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle.
This double check lock is only necessary if you are worried about many threads calling the singleton simultaneously, or the cost of obtaining a lock in general. Its purpose is to prevent unnecessary synchronization, thereby keeping your code fast in a multi-threaded environment.
By the way, this is not the best way to create thread-safe Singleton, you can use Enum as Singleton, which provides inbuilt thread-safety during instance creation. Another way is to use a static holder pattern. That's all about double checked locking of Singleton class in Java.
In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With