Lock-free lazy initialization
Replace double-checked locking with StableValue for lazy singletons.
Porównanie kodu
✕ 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();
}
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
synchronized + volatile
Nowoczesne podejście
StableValue
Od JDK
25
Poziom trudności
Zaawansowany
Wsparcie JDK
Lock-free lazy initialization
Preview
Preview in JDK 25 (JEP 502, StableValue). Requires --enable-preview.
Jak to działa
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.
Powiązana dokumentacja