Skip to content

Commit 9240d80

Browse files
authoredApr 13, 2024
docs: add explanation for Double-Checked Locking (#2914)

File tree

3 files changed

+115
-14
lines changed

3 files changed

+115
-14
lines changed
 

‎double-checked-locking/README.md

Lines changed: 113 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,124 @@
11
---
2-
title: Double Checked Locking
3-
category: Idiom
2+
title: Double-Checked Locking
3+
category: Concurrency
44
language: en
55
tag:
6-
- Performance
6+
- Optimization
7+
- Performance
78
---
89

910
## Intent
10-
Reduce the overhead of acquiring a lock by first testing the
11-
locking criterion (the "lock hint") without actually acquiring the lock. Only
12-
if the locking criterion check indicates that locking is required does the
13-
actual locking logic proceed.
11+
12+
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.
13+
14+
## Explanation
15+
16+
Real world example
17+
18+
> 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.
19+
20+
In plain words
21+
22+
> 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.
23+
24+
Wikipedia says
25+
26+
> 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.
27+
28+
**Programmatic Example**
29+
30+
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:
31+
32+
Check if the object is initialized (first check): If it is, return it immediately.
33+
34+
```java
35+
if (heavy == null) {
36+
// ...
37+
}
38+
```
39+
40+
Synchronize the block of code where the object is created: This ensures that only one thread can create the object.
41+
42+
```java
43+
synchronized (this) {
44+
// ...
45+
}
46+
```
47+
48+
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.
49+
50+
```java
51+
if (heavy == null) {
52+
heavy = new Heavy();
53+
}
54+
```
55+
56+
Return the created object.
57+
58+
```java
59+
return heavy;
60+
```
61+
62+
Here's the complete code for the HolderThreadSafe class:
63+
64+
```java
65+
public class HolderThreadSafe {
66+
67+
private Heavy heavy;
68+
69+
public HolderThreadSafe() {
70+
LOGGER.info("Holder created");
71+
}
72+
73+
public synchronized Heavy getHeavy() {
74+
if (heavy == null) {
75+
synchronized (this) {
76+
if (heavy == null) {
77+
heavy = new Heavy();
78+
}
79+
}
80+
}
81+
return heavy;
82+
}
83+
}
84+
```
85+
86+
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.
1487

1588
## Class diagram
16-
![alt text](./etc/double_checked_locking_1.png "Double Checked Locking")
89+
90+
![Double-Check Locking](./etc/double_checked_locking_1.png "Double-Checked Locking")
1791

1892
## Applicability
19-
Use the Double Checked Locking pattern when
2093

21-
* 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.
22-
* 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.
94+
This pattern is used in scenarios where:
95+
96+
* There is a significant performance cost associated with acquiring a lock, and
97+
* The lock is not frequently needed.
98+
99+
## Known Uses
100+
101+
* Singleton pattern implementation in multithreading environments.
102+
* Lazy initialization of resource-intensive objects in Java applications.
103+
104+
## Consequences
105+
106+
Benefits:
107+
108+
* Performance gains from avoiding unnecessary locking after the object is initialized.
109+
* Thread safety is maintained for critical initialization sections.
110+
111+
Trade-offs:
112+
113+
* Complex implementation can lead to mistakes, such as incorrect publishing of objects due to memory visibility issues.
114+
* In Java, it can be redundant or broken in some versions unless volatile variables are used with care.
115+
116+
## Related Patterns
117+
118+
* [Singleton](https://java-design-patterns.com/patterns/singleton/): Double-Checked Locking is often used in implementing thread-safe Singletons.
119+
* [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Shares the concept of delaying object creation until necessary.
120+
121+
## Credits
122+
123+
* [Java Concurrency in Practice](https://amzn.to/4aIAPKa)
124+
* [Effective Java](https://amzn.to/3xx7KDh)

‎double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ class AppTest {
3535

3636
/**
3737
* Issue: Add at least one assertion to this test case.
38-
*
3938
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
4039
* throws an exception.
4140
*/

‎double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ void tearDown() {
8080
* item limit.
8181
*/
8282
@Test
83-
void testAddItem() throws Exception {
83+
void testAddItem() {
8484
assertTimeout(ofMillis(10000), () -> {
8585
// Create a new inventory with a limit of 1000 items and put some load on the add method
8686
final var inventory = new Inventory(INVENTORY_SIZE);
@@ -109,7 +109,7 @@ void testAddItem() throws Exception {
109109
}
110110

111111

112-
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
112+
private static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
113113
private final List<ILoggingEvent> log = new LinkedList<>();
114114

115115
public InMemoryAppender(Class clazz) {

0 commit comments

Comments
 (0)
Please sign in to comment.