GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev โ Stable values | java.evolved
Concurrency
Advanced
Thread-safe lazy initialization without volatile or synchronized. Code Comparison
โ Java 8
private volatile Logger logger;
Logger getLogger() {
if (logger == null) {
synchronized (this) {
if (logger == null)
logger = createLogger();
}
}
return logger;
}
โ Java 25 (Preview)
private final StableValue<Logger> logger =
StableValue.of(this::createLogger);
Logger getLogger() {
return logger.get();
}
See a problem with this code? Let us know.
Why the modern way wins
๐งน
Zero boilerplateNo volatile, synchronized, or null checks. โก
JVM-optimizedThe JVM can fold the value after initialization. ๐ก๏ธ
Guaranteed onceThe supplier runs exactly once, even under contention. Old Approach
Double-Checked Locking
Modern Approach
StableValue
Since JDK
25
Difficulty
Advanced
JDK Support
Stable values
Preview
Preview in JDK 25 (JEP 502). Requires --enable-preview. How it works
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. Related Documentation
Proof
Related patterns
Concurrency
Beginner
Virtual threadsJava 8
Thread thread = new Thread(() -> {
System.out.println("hello");
});
thread.start();
thread.join();
Java 21+
Thread.startVirtualThread(() -> {
IO.println("hello");
}).join();
JDK 21+
โ
Concurrency
Advanced
Structured concurrencyJava 8
ExecutorService exec =
Executors.newFixedThreadPool(2);
Future<User> u = exec.submit(this::fetchUser);
Future<Order> o = exec.submit(this::fetchOrder);
try {
return combine(u.get(), o.get());
} finally { exec.shutdown(); }
Java 25 (Preview)
try (var scope = new StructuredTaskScope
.ShutdownOnFailure()) {
var u = scope.fork(this::fetchUser);
var o = scope.fork(this::fetchOrder);
scope.join().throwIfFailed();
return combine(u.get(), o.get());
}
JDK 25+
โ
Concurrency
Advanced
Scoped valuesJava 8
static final ThreadLocal<User> CURRENT =
new ThreadLocal<>();
void handle(Request req) {
CURRENT.set(authenticate(req));
try { process(); }
finally { CURRENT.remove(); }
}
Java 25
static final ScopedValue<User> CURRENT =
ScopedValue.newInstance();
void handle(Request req) {
ScopedValue.where(CURRENT,
authenticate(req)
).run(this::process);
}
JDK 25+
โ
|
| You are visitor 01402503 โ GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร600. No cookies required. |