Lock-free lazy initialization
Replace double-checked locking with StableValue for lazy singletons.
Code Comparison
✕ Java 8
class Config {
private static volatile Config inst;
static Config get() {
if (inst == null) {
synchronized (Config.class) {
if (inst == null)
inst = load();
}
}
return inst;
}
}
✓ Java 25 (Preview)
class Config {
private static final
StableValue<Config> INST =
StableValue.of(Config::load);
static Config get() {
return INST.get();
}
}
Why the modern way wins
No boilerplate
No volatile, synchronized, or double-null-check.
Faster reads
JVM can constant-fold after initialization.
Provably correct
No subtle ordering bugs — the JVM handles it.
Old Approach
synchronized + volatile
Modern Approach
StableValue
Since JDK
25
Difficulty
advanced
JDK Support
Lock-free lazy initialization
Available
Preview in JDK 25 (JEP 502, StableValue). Requires --enable-preview.
How it works
StableValue encapsulates the lazy initialization pattern with correct thread safety. The JVM can optimize the read path after initialization, potentially making it faster than volatile reads.