ArticleslgStudy

computer science

Double-checked locking

Double-checked locking is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Double-checked locking rather than just read about it. In short: 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. Locking occurs only if the locking criterion check indicates that locking is required.

Key takeaways

  • Double-checked locking belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Double-checked locking to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Double-checked locking from memory before moving on to harder problems.

Reference excerpt

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. 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, 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. There are valid forms of the pattern, including the use of the volatile keyword in Java and explicit memory barriers in C++. 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.

Motivation and original pattern Consider, for example, this code segment in the Java programming language:

The problem is that this does not work when using multiple threads. A lock must be obtained in case two threads call bar() 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. Synchronizing with a lock can fix this, as is shown in the following example:

This is correct and will most likely have sufficient performance. However, the first call to bar() 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 after the initialization has been completed seems unnecessary. Many programmers, including the authors of the double-checked locking design pattern, have attempted to optimize this situation in the following manner:

Check that the variable is initialized (without obtaining the lock). 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.

Intuitively, this algorithm is an efficient solution to the problem. But if the pattern is not written carefully, it will have a data race. 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 (or so it appears), 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 (either because A has not finished initializing it or because some of the initialized values in the object have not yet percolated to the memory B uses (cache coherence)), the program will likely crash. Most runtimes have memory barriers or other methods for managing memory visibility across execution units. Without a detailed understanding of the language's behavior in this area, the algorithm is difficult to implement correctly. One of the dangers of using double-checked locking is that even a naive implementation will appear to work most of the time: 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.

Usage in C++ For the singleton pattern, double-checked locking is not needed:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

C++11 and beyond also provide a built-in double-checked locking pattern in the form of std::once_flag and std::call_once:

If one wishes to manually implement an explicit and proper double-checked idiom instead of the trivially working example above (for instance because Visual Studio before the 2015 release did not implement the C++11 standard's language about concurrent initialization quoted above), one needs at least atomic operations with acquire/release memory ordering as in this code (explicit memory fence statements also work but may use slower CPU instructions e.g. on ARM64):

Usage in POSIX pthread_once() must be used to initialize library (or sub-module) code when its API does not have a dedicated initialization procedure required to be called in single-threaded mode.

Usage in Go

Usage in Java As of J2SE 5.0, the volatile keyword is defined to create a memory barrier. This allows a solution that ensures that multiple threads handle the singleton instance correctly. This new idiom is described in [3] and [4].

Note the local variable local, which seems unnecessary. The effect of this is that in cases where bar is already initialized (i.e., most of the time), the volatile field is only accessed once (due to return local;" instead of return bar;), which can improve the method's overall performance by as much as 40 percent. Java 9 introduced the java.lang.invoke.VarHandle 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 (field accesses no longer participate in the synchronization order, the global order of accesses to volatile fields).

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Double-checked locking

Start with the simplest possible case. Write down what Double-checked locking claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Double-checked locking before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Double-checked locking ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Double-checked locking

In research
Double-checked locking appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Double-checked locking in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Double-checked locking is common in secondary-school and first-year university syllabi. It links to neighbouring topics Concurrency control, Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Double-checked locking outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Double-checked locking” →

How to study Double-checked locking in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Double-checked locking means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Double-checked locking out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Double-checked locking in simple terms?

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. Locking occurs only if the locking criteri…

Why does Double-checked locking matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Double-checked locking?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Double-checked locking.

Tags

  • Concurrency control
  • Software design patterns

Keep exploring