Double-checked locking

In software engineering, double-checked locking (also known as "double-checked locking optimization"[1]) 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. Locking occurs only if the locking criterion check indicates that locking is required.

The original form of the pattern, appearing in Pattern Languages of Program Design 3,[2] has data races, depending on the memory model in use, and it is hard to get right. Some consider it to be an anti-pattern.[3] There are valid forms of the pattern, including the use of the volatile keyword in Java and explicit memory barriers in C++.[4]

The pattern 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.

  1. ^ Schmidt, D et al. Pattern-Oriented Software Architecture Vol 2, 2000 pp353-363
  2. ^ Pattern languages of program design. 3 (PDF) (Nachdr. ed.). Reading, Mass: Addison-Wesley. 1998. ISBN 978-0201310115.
  3. ^ Gregoire, Marc (24 February 2021). Professional C++. John Wiley & Sons. ISBN 978-1-119-69545-5.
  4. ^ David Bacon et al. The "Double-Checked Locking is Broken" Declaration.