forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstable-values.yaml
More file actions
57 lines (56 loc) · 1.74 KB
/
stable-values.yaml
File metadata and controls
57 lines (56 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
---
id: 49
slug: "stable-values"
title: "Stable values"
category: "concurrency"
difficulty: "advanced"
jdkVersion: "25"
oldLabel: "Java 8"
modernLabel: "Java 25 (Preview)"
oldApproach: "Double-Checked Locking"
modernApproach: "StableValue"
oldCode: |-
private volatile Logger logger;
Logger getLogger() {
if (logger == null) {
synchronized (this) {
if (logger == null)
logger = createLogger();
}
}
return logger;
}
modernCode: |-
private final StableValue<Logger> logger =
StableValue.of(this::createLogger);
Logger getLogger() {
return logger.get();
}
summary: "Thread-safe lazy initialization without volatile or synchronized."
explanation: "StableValue provides a lazily initialized, immutable value with built-in\
\ thread safety. No double-checked locking, no volatile fields, no synchronized\
\ blocks. The JVM can even optimize the read path after initialization."
whyModernWins:
- icon: "🧹"
title: "Zero boilerplate"
desc: "No volatile, synchronized, or null checks."
- icon: "⚡"
title: "JVM-optimized"
desc: "The JVM can fold the value after initialization."
- icon: "🛡️"
title: "Guaranteed once"
desc: "The supplier runs exactly once, even under contention."
support:
state: "preview"
description: "Preview in JDK 25 (JEP 502). Requires --enable-preview."
prev: "concurrency/scoped-values"
next: "concurrency/completablefuture-chaining"
related:
- "concurrency/virtual-threads"
- "concurrency/structured-concurrency"
- "concurrency/scoped-values"
docs:
- title: "Stable Values (JEP 502)"
href: "https://openjdk.org/jeps/502"
- title: "StableValue"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/StableValue.html"