Skip to content

Explanation for double-checked locking #2914

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 113 additions & 11 deletions double-checked-locking/README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,124 @@
---
title: Double Checked Locking
category: Idiom
title: Double-Checked Locking
category: Concurrency
language: en
tag:
- Performance
- Optimization
- Performance
---

## Intent
Reduce the overhead of acquiring a lock by first testing the
locking criterion (the "lock hint") without actually acquiring the lock. Only
if the locking criterion check indicates that locking is required does the
actual locking logic proceed.

The Double-Checked Locking pattern aims to reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') without actually acquiring the lock. Only if the locking criterion check indicates that locking is necessary does the actual locking logic proceed.

## Explanation

Real world example

> In a company with a high-value equipment room, employees first check a visible sign to see if the room is locked. If the sign shows it's unlocked, they enter directly; if locked, they use a security keycard for access. This two-step verification process efficiently manages security without unnecessary use of the electronic lock system, mirroring the Double-Checked Locking pattern used in software to minimize resource-intensive operations.

In plain words

> The Double-Checked Locking pattern in software minimizes costly locking operations by first checking the lock status in a low-cost manner before proceeding with a more resource-intensive lock, ensuring efficiency and thread safety during object initialization.

Wikipedia says

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

**Programmatic Example**

The Double-Checked Locking pattern is used in the HolderThreadSafe class to ensure that the Heavy object is only created once, even when accessed from multiple threads. Here's how it works:

Check if the object is initialized (first check): If it is, return it immediately.

```java
if (heavy == null) {
// ...
}
```

Synchronize the block of code where the object is created: This ensures that only one thread can create the object.

```java
synchronized (this) {
// ...
}
```

Check again if the object is initialized (second check): If another thread has already created the object by the time the current thread enters the synchronized block, return the created object.

```java
if (heavy == null) {
heavy = new Heavy();
}
```

Return the created object.

```java
return heavy;
```

Here's the complete code for the HolderThreadSafe class:

```java
public class HolderThreadSafe {

private Heavy heavy;

public HolderThreadSafe() {
LOGGER.info("Holder created");
}

public synchronized Heavy getHeavy() {
if (heavy == null) {
synchronized (this) {
if (heavy == null) {
heavy = new Heavy();
}
}
}
return heavy;
}
}
```

In this code, the Heavy object is only created when the getHeavy() method is called for the first time. This is known as lazy initialization. The double-checked locking pattern is used to ensure that the Heavy object is only created once, even when the getHeavy() method is called from multiple threads simultaneously.

## Class diagram
![alt text](./etc/double_checked_locking_1.png "Double Checked Locking")

![Double-Check Locking](./etc/double_checked_locking_1.png "Double-Checked Locking")

## Applicability
Use the Double Checked Locking pattern when

* there is a concurrent access in object creation, e.g. singleton, where you want to create single instance of the same class and checking if it's null or not maybe not be enough when there are two or more threads that checks if instance is null or not.
* there is a concurrent access on a method where method's behaviour changes according to the some constraints and these constraint change within this method.
This pattern is used in scenarios where:

* There is a significant performance cost associated with acquiring a lock, and
* The lock is not frequently needed.

## Known Uses

* Singleton pattern implementation in multithreading environments.
* Lazy initialization of resource-intensive objects in Java applications.

## Consequences

Benefits:

* Performance gains from avoiding unnecessary locking after the object is initialized.
* Thread safety is maintained for critical initialization sections.

Trade-offs:

* Complex implementation can lead to mistakes, such as incorrect publishing of objects due to memory visibility issues.
* In Java, it can be redundant or broken in some versions unless volatile variables are used with care.

## Related Patterns

* [Singleton](https://java-design-patterns.com/patterns/singleton/): Double-Checked Locking is often used in implementing thread-safe Singletons.
* [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Shares the concept of delaying object creation until necessary.

## Credits

* [Java Concurrency in Practice](https://amzn.to/4aIAPKa)
* [Effective Java](https://amzn.to/3xx7KDh)
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ class AppTest {

/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ void tearDown() {
* item limit.
*/
@Test
void testAddItem() throws Exception {
void testAddItem() {
assertTimeout(ofMillis(10000), () -> {
// Create a new inventory with a limit of 1000 items and put some load on the add method
final var inventory = new Inventory(INVENTORY_SIZE);
Expand Down Expand Up @@ -109,7 +109,7 @@ void testAddItem() throws Exception {
}


private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>();

public InMemoryAppender(Class clazz) {
Expand Down
Loading