What is Java's LazyConstant, a preview API at JDK 27, and what does it add over a holder class or double-checked locking?
answer
- deferred immutability
- computing function fixed at construction
- holder idiom: static fields, one class each
- mutable volatile field cannot be folded
- folding needs a static final chain
basics
~20 sLazyConstant, a JDK 27 preview API, runs its computing function at most once, on first get(). Unlike a holder class it works on instance fields; unlike double-checked locking its content can be constant-folded when reached from a static final field.
solid answer
~50 s`LazyConstant<T>` (third preview at JDK 27, JEP 531) is created with `LazyConstant.of(supplier)`. The first `get()` runs that computing function on the caller's thread, competing threads block, and the content never changes afterwards. A holder class is also lazy and also allows constant folding, but it fits only static fields and costs one class per field; a lazy constant works on instance fields too. Double-checked locking needs a mutable `volatile` field, which the JVM cannot constant-fold, plus locking code you must get right. The JVM may fold reads of an initialized lazy constant only when a `static final` field reaches it, directly or through trusted fields, so an ordinary final instance field gets laziness but not folding. In exchange you accept no `null` content, a function fixed at construction and, at 27, a failure that sticks.
code
java · 34 linesclass Report {
// static final: eligible for constant folding once initialized
private static final LazyConstant<String> TEMPLATE =
LazyConstant.of(() -> {
System.out.println("loading template");
return "Total: %d";
});
// Final instance field of an ordinary class: lazy, computed at most once per Report, not folded
private final LazyConstant<String> summary =
LazyConstant.of(this::buildSummary);
private final int total;
Report(int total) {
this.total = total;
}
private String buildSummary() {
System.out.println("building summary");
return TEMPLATE.get().formatted(total);
}
String summary() {
return summary.get();
}
public static void main(String[] args) {
Report report = new Report(42);
System.out.println("created"); // nothing computed yet
System.out.println(report.summary()); // builds, loads the template, prints Total: 42
System.out.println(report.summary()); // prints Total: 42, computes nothing
}
}go deeper
Recall the shape: LazyConstant.of takes a function, get() runs it once on first use, and the value never changes afterwards. Know that it is a preview API at JDK 27 and needs the --enable-preview flag.
Explain the comparison: a holder class fits only static fields and needs one class per value, while double-checked locking keeps a mutable volatile field that cannot be folded. Say what a lazy constant does about each.
Be precise on folding: the JVM may fold only through a static final chain of trusted fields, so instance fields on ordinary classes gain laziness alone. Measure before claiming a speedup, and plan for a failure that sticks.
Treat adoption as a release-policy decision: preview class files run only on the release that built them, and each re-preview has changed the API. Weigh that against keeping a holder class or double-checked locking until the API is final.
## What a lazy constant is A **lazy constant** is an object of type `java.lang.LazyConstant<T>` that holds one value, its **content**, and computes it on demand. You create it with the static factory `LazyConstant.of(Supplier)`, passing a **computing function**, usually a lambda. Nothing runs at construction. The first call to `get()` runs the function, stores the result and returns it; later calls return the same content. JEP 531 calls this **deferred immutability**: the value is fixed once it exists, but it need not exist by the end of a constructor or static initializer, as a `final` field's value must. Its status at JDK 27 matters as much as its behaviour: - It is a **preview API**, in its third preview (JEP 531). No release has it in final form. - javac rejects it unless preview features are enabled, as in `--enable-preview --release 27`, and the `java` launcher needs `--enable-preview` as well. - It first previewed in JDK 25 under another name, `StableValue` (JEP 502), and JDK 26 renamed it (JEP 526). On JDK 25 LTS the type `LazyConstant` does not exist, and the nearest form is `StableValue.supplier()`, which also takes its function at construction. ## What `get()` guarantees When threads race on an uninitialized constant: 1. One thread is selected and runs the computing function itself. 2. The others block until the constant is initialized or the computation fails. 3. The result becomes the content, and the function is no longer strongly referenced, so it can be collected. 4. Readers see that content safely published, because the computation happens-before the read. No timeout exists, so a function that blocks indefinitely may block the others indefinitely too. ## What it adds over a holder class The **class-holder idiom** keeps the value in a `static final` field of a nested class and relies on the JVM initializing that class lazily; how it works is covered with double-checked locking. It is lazy, computes at most once and, as JEP 531 says, allows **constant folding**, where the JVM stops re-reading a value and uses the one it has already seen. So folding is not the reason to switch. The differences are reach and cost: - **Instance fields.** A holder fits only static fields, so it cannot give each object its own lazy value. A lazy constant can. - **One class per value.** Each field needs its own holder class, which JEP 531 says makes applications harder to read, slower to start and heavier on memory. ## What it adds over double-checked locking **Double-checked locking** keeps the value in a mutable `volatile` field guarded by a lock; why it needs `volatile` has its own question. A lazy constant adds: - **Constant folding.** The JVM cannot trust a mutable field never to change, so JEP 531 rules folding out for this idiom. A lazy constant's content sits in a private field annotated with the JDK-internal `@Stable`, which tells the JVM the field will not change after its one update. - **Less to get wrong.** The field holding the constant can be `final`, with no `volatile`, no lock code and no rule that every access must go through a getter. - **Per-element laziness.** JEP 531's hand-written version over an array takes a `VarHandle` and a mutex per element; `List.ofLazy` replaces all of it. | | Holder class | Double-checked locking | `LazyConstant` | |---|---|---|---| | Instance fields | No | Yes | Yes | | Constant folding | Allowed | Not possible | Allowed through a `static final` chain, once initialized | | Computation fails | Class stays erroneous: later uses throw `NoClassDefFoundError` | Next call tries again | `NoSuchElementException`, never recomputed | | Result can be `null` | Yes | Only with an extra marker | No | ## Where the folding claim stops This is the part most answers overstate. The Javadoc says a JVM *may* elide reads of an initialized lazy constant's content, and that this is only possible in two cases: - a `static final` field refers to the lazy constant directly, or - a chain from a `static final` field reaches it through **trusted fields**: `static final` fields, record fields, or final instance fields in hidden classes. An ordinary class's final instance field is not trusted, because core reflection can still change it. So `private final LazyConstant<String> summary` on a plain class gets laziness and at-most-once computation but not folding: each `get()` stays an acquire read of the private `constant` field in the JDK-internal `LazyConstantImpl`. Storing an array in a lazy constant does not speed up access to its elements either; the Javadoc points to a lazy list instead. ## What you give up - **`null`.** A function that returns `null` fails; wrap a nullable value in `Optional`. - **Call-site arguments.** The function is fixed at construction, so it cannot use what a caller knows at `get()`. JEP 531's Future Work names this gap. - **Retry.** At JDK 27 a function that throws leaves the constant in an error state for good, and `get()` throws `NoSuchElementException` from then on. - **Clearing.** Content cannot be removed and stays strongly referenced while the constant is reachable, which the Javadoc flags as a possible leak. - **A settled API.** Each re-preview so far has changed it, and class files compiled with preview features run only on that release. JEP 547, a candidate when this was written, proposes a further preview with no changes in JDK 28.
- Does a LazyConstant in a final instance field of an ordinary class get constant-folded at JDK 27?No. The Javadoc allows folding only when a `static final` field reaches the constant, directly or through trusted fields: `static final` fields, record fields, or final instance fields in hidden classes. An ordinary final instance field is not trusted, because core reflection can change it. You still get laziness and at-most-once computation. Internally, JDK 27's `get()` reads a private field with acquire semantics, but that is not a contract: the Javadoc gives no further memory-ordering guarantee for repeat calls.
- If a holder class also allows constant folding, when is it still the simpler choice?When the value is static, there are only one or two of them, and you cannot depend on a preview API. A holder needs no flags, and its class files are not tied to one JDK release. JEP 531's case against it is that it fits only static fields and needs a class per field, so it loses its appeal as values multiply or belong to instances.
- What happens to other threads while one thread runs a lazy constant's computing function?They block until the constant is initialized or the computation fails, then read the content or get a `NoSuchElementException`, without running the function themselves. The Javadoc provides no timeout or cancellation, so a function that blocks indefinitely may block them indefinitely. Interrupting the computing thread does not cancel the computation, and `get()` neither clears the interrupt status nor throws `InterruptedException`.
- A holder class cannot be constant-folded, so folding is the main reason to replace it.
- Any final LazyConstant field is constant-folded, including instance fields of ordinary classes.
- LazyConstant is final in JDK 27, so it needs no compiler or launcher flags.
- LazyConstant adds a language keyword for declaring lazy fields.
- Racing threads may each run the computing function, and only one result is kept.
- A lazy constant can store null as long as the function returns it deliberately.
- LazyConstant
- not finalpre-release 26
Assumes JDK 27, where LazyConstant is a preview API in its third preview; JDK 25 LTS has the earlier StableValue form and no LazyConstant type.
context
- LazyConstant (Java SE 27 & JDK 27)docs.oracle.com
- JEP 531: Lazy Constants (Third Preview)openjdk.org
- Chapter 12. Executiondocs.oracle.com