In software engineering, double-checked locking is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion before acquiring the lock. Locking occurs only if the locking criterion check indicates that locking is required. The pattern, when implemented in some language/hardware combinations, can be unsafe. At times, it can be considered an anti-pattern. It is typically used to reduce locking overhead when implementing "lazy initialization" in a multi-threaded environment, especially as part of the Singleton pattern. Lazy initialization avoids initializing a value until the first time it is accessed.
Usage in C++11
For the singleton pattern, double-checked locking is not needed: Singleton& GetInstance
If one wished to use the double-checked idiom instead of the trivially working example above, one needs to use acquire and release fences:
include
include
class Singleton ; Singleton* Singleton::GetInstance
Usage in Golang
package main import "sync" var arrOnce sync.Once var arr int // getArr retrieves arr, lazily initializing on first call. Double-checked // locking is implemented with the sync.Once library function. The first // goroutine to win the race to call Do will initialize the array, while // others will block until Do has completed. After Do has run, only a // single atomic comparison will be required to get the array. func getArr int func main
The problem is that this does not work when using multiple threads. A lock must be obtained in case two threads call getHelper simultaneously. Otherwise, either they may both try to create the object at the same time, or one may wind up getting a reference to an incompletely initialized object. The lock is obtained by expensive synchronizing, as is shown in the following example. // Correct but possibly expensive multithreaded version class Foo
However, the first call to getHelper will create the object and only the few threads trying to access it during that time need to be synchronized; after that all calls just get a reference to the member variable. Since synchronizing a method could in some extreme cases decrease performance by a factor of 100 or higher, the overhead of acquiring and releasing a lock every time this method is called seems unnecessary: once the initialization has been completed, acquiring and releasing the locks would appear unnecessary. Many programmers have attempted to optimize this situation in the following manner:
Check that the variable is initialized. If it is initialized, return it immediately.
Obtain the lock.
Double-check whether the variable has already been initialized: if another thread acquired the lock first, it may have already done the initialization. If so, return the initialized variable.
Otherwise, initialize and return the variable.
// Broken multithreaded version // "Double-Checked Locking" idiom class Foo
Intuitively, this algorithm seems like an efficient solution to the problem. However, this technique has many subtle problems and should usually be avoided. For example, consider the following sequence of events:
Thread A notices that the value is not initialized, so it obtains the lock and begins to initialize the value.
Due to the semantics of some programming languages, the code generated by the compiler is allowed to update the shared variable to point to a partially constructed object before A has finished performing the initialization. For example, in Java if a call to a constructor has been inlined then the shared variable may immediately be updated once the storage has been allocated but before the inlined constructor initializes the object.
Thread B notices that the shared variable has been initialized, and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B, the program will likely crash.
One of the dangers of using double-checked locking in J2SE 1.4 is that it will often appear to work: it is not easy to distinguish between a correct implementation of the technique and one that has subtle problems. Depending on the compiler, the interleaving of threads by the scheduler and the nature of other concurrent system activity, failures resulting from an incorrect implementation of double-checked locking may only occur intermittently. Reproducing the failures can be difficult. As of J2SE 5.0, this problem has been fixed. The volatile keyword now ensures that multiple threads handle the singleton instance correctly. This new idiom is described in and . // Works with acquire/release semantics for volatile in Java 1.5 and later // Broken under Java 1.4 and earlier semantics for volatile class Foo
Note the local variable "localRef", which seems unnecessary. The effect of this is that in cases where helper is already initialized, the volatile field is only accessed once, which can improve the method's overall performance by as much as 40 percent. Java 9 introduced the class, which allows use of relaxed atomics to access fields, giving somewhat faster reads on machines with weak memory models, at the cost of more difficult mechanics and loss of sequential consistency. // Works with acquire/release semantics for VarHandles introduced in Java 9 class Foo
This relies on the fact that nested classes are not loaded until they are referenced. Semantics of final field in Java 5 can be employed to safely publish the helper object without using volatile: public class FinalWrapper public class Foo
The local variable tempWrapper is required for correctness: simply using helperWrapper for both null checks and the return statement could fail due to read reordering allowed under the Java Memory Model. Performance of this implementation is not necessarily better than the volatile implementation.
Usage in C#
Double-checked locking can be implemented efficiently in.NET. A common usage pattern is to add double-checked locking to Singleton implementations: public class MySingleton
In this example, the "lock hint" is the mySingleton object which is no longer null when fully constructed and ready for use. In.NET Framework 4.0, the Lazy<T> class was introduced, which internally uses double-checked locking by default to store either the exception that was thrown during construction, or the result of the function that was passed to Lazy<T>: public class MySingleton