✅ TLDR
▪️ LazyConstant = compute once, thread-safe, immutable-after-init
▪️ Keeps lazy initialization and enables final-like JVM optimizations
▪️ Perfect for expensive objects you don’t want to build at startup
🔸 THE PROBLEM: “FINAL” IS FAST… BUT EAGER
▪️ final fields must be set early (constructor / ).
▪️ Great for immutability… but can slow startup when objects are expensive (loggers, configs, caches).
🔸 THE USUAL WORKAROUNDS ARE… FRAGILE
▪️ Lazy init with mutable fields ⇒ tricky invariants + thread-safety headaches
▪️ Double-checked locking ⇒ verbose + easy to get wrong
▪️ Concurrent maps ⇒ safe-ish, but JVM can’t treat values as “true constants”
🔸 JEP 526 BRINGS “DEFERRED IMMUTABILITY”
▪️ New preview API: java.lang.LazyConstant (JDK 26, Second Preview)
▪️ Value computed on first get()
▪️ Computed at most once, even with concurrent calls (one “winner”)
▪️ After init, treated as unmodifiable + JVM can apply constant-folding optimizations (when referenced from a final field)
🔸 THE “AHA” EXAMPLE
class OrderController {
private final LazyConstant logger =
LazyConstant.of(() -> Logger.create(OrderController.class));
void submitOrder() {
logger.get().info("order submitted");
}
}
▪️ Startup stays light ✅
▪️ First use pays the cost ✅
▪️ Next calls are fast + JIT-friendly ✅
🔸 BONUS: LAZY LISTS & MAPS
▪️ List.ofLazy(size, index -> value) for pools / slots
▪️ Map.ofLazy(keys, key -> value) for keyed lazy init
🔸 WHAT CHANGED VS JEP 502 (JDK 25 PREVIEW)
▪️ Renamed from StableValue → LazyConstant
▪️ Dropped low-level setters (trySet, setOrThrow, …) → focus on high-level use cases
🔸 HOW TO TRY IT (PREVIEW)
▪️ javac --release 26 --enable-preview ...
▪️ java --enable-preview ...
🎯 TAKEAWAYS
▪️ Use it when you want startup speed + immutability + concurrency safety
▪️ Store the LazyConstant in a final field for best optimization potential
▪️ It’s preview: expect tweaks until it graduates
#Java #OpenJDK #JDK26 #JEP526 #Performance #Concurrency #Immutability #StartupTime #CoreLibraries #PreviewFeatures
Go further with Java certification:
Java👇
Spring👇
SpringBook👇
JavaBook👇