Files
javademos/docs/06-lazy-constants.md

1.6 KiB

6. Lazy constants (JEP 531, third preview)

Prev: 5. Primitive patterns · Next: 7. Structured concurrency

Compile and run with --enable-preview --release 27. Source: LazyDemo, transcript 22.

A lazy constant holds a value that is computed the first time somebody asks for it, exactly once, even when many threads ask at the same instant, after which the JVM may treat it like a final field. It replaces the hand-written holder-class idiom and the double-checked-locking field.

static final LazyConstant<Settings> SETTINGS = LazyConstant.of(LazyDemo::loadSettings);
Settings s = SETTINGS.get();   // computes on first call, returns the same instance afterwards

What the transcript shows, each backed by an assertion: the supplier ran once; 64 virtual threads racing on get() caused one initialisation; List.ofLazy(5, i -> ...) computed only element 3 after get(3); Map.ofLazy(keys, f) computed only the requested key; Set.ofLazy(Set.of(2..7), isPrime) answers contains on demand.

What changed since 26 (the compile errors)

  • LazyConstant.orElse(...) and isInitialized() are gone in 27 (20-broken-lazy26.txt; the class is LazyConstant in both, the old StableValue was already removed in 26 - 52).
  • Set.ofLazy(Set, Predicate) is new in 27 (62, 51).

Prev: 5. Primitive patterns · Next: 7. Structured concurrency