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

24 lines
1.6 KiB
Markdown

# 6. Lazy constants (JEP 531, third preview)
Prev: [5. Primitive patterns](05-primitive-patterns.md) · Next: [7. Structured concurrency](07-structured-concurrency.md)
Compile and run with `--enable-preview --release 27`. Source: [`LazyDemo`](../jep-tour/src/LazyDemo.java), transcript [22](output/22-lazy.txt).
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.
```java
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](output/20-broken-lazy26.txt); the class is `LazyConstant` in both, the old `StableValue` was already removed in 26 - [52](output/52-api-diff-25-to-26.txt)).
* `Set.ofLazy(Set, Predicate)` is new in 27 ([62](output/62-new-api.txt), [51](output/51-api-diff-26-to-27.txt)).
Prev: [5. Primitive patterns](05-primitive-patterns.md) &middot; Next: [7. Structured concurrency](07-structured-concurrency.md)