How do List.ofLazy, Map.ofLazy and Set.ofLazy extend LazyConstant, what happens when a computing function throws, and what changed from StableValue?
answer
- one lazy slot per element
- shape fixed at construction
- Set.ofLazy computes membership with a Predicate
- error state, never recomputed at 27
- cause only on the first failure
basics
~20 sList.ofLazy, Map.ofLazy and Set.ofLazy behave like one lazy constant per index, key or candidate. At JDK 27 a throwing function leaves that slot in an error state: NoSuchElementException on each access, never recomputed. JDK 26 turned StableValue into LazyConstant, minus its setters.
solid answer
~40 s`List.ofLazy(size, fn)`, `Map.ofLazy(keys, fn)` and `Set.ofLazy(candidates, predicate)` return unmodifiable collections that behave like one lazy constant per index, key or candidate: each slot computes independently, at most once, and is eligible for constant folding. At JDK 27, if the function throws, the first caller gets `NoSuchElementException` with the original exception as its cause; later accesses to that slot get one with no cause, naming the original class in its message, and the function never runs again. JDK 25 and 26 behaved differently: the exception reached the caller and a later call could retry. The API began in JDK 25 as `StableValue`. JDK 26 renamed it, removed `orElseSet`, `setOrThrow`, `trySet`, `function` and `intFunction`, moved the factories to `List` and `Map`, and banned `null`. JDK 27 removed `isInitialized` and `orElse` and added `Set.ofLazy`.
code
java · 27 linesimport java.util.List;
import java.util.NoSuchElementException;
class LazyFailure {
public static void main(String[] args) {
List<String> parts = List.ofLazy(3, i -> {
System.out.println("computing " + i);
if (i == 1) {
throw new IllegalArgumentException("no part " + i);
}
return "part-" + i;
});
System.out.println(parts.size()); // 3, nothing computed
System.out.println(parts.get(0)); // computing 0, then part-0
for (int attempt = 1; attempt <= 2; attempt++) {
try {
parts.get(1); // "computing 1" prints only on attempt 1
} catch (NoSuchElementException e) {
System.out.println(attempt + ": cause=" + e.getCause());
}
}
System.out.println(parts.get(2)); // index 2 is unaffected: computing 2, then part-2
}
}go deeper
Recall the three factories and what each computes: a list element by index, a map value by key, and a set's membership for a candidate. Remember that the collections are unmodifiable and still a preview API at JDK 27.
Explain what runs when: get on a list computes one index, size on a lazy set computes every candidate, and toString on a collection can run the function. Then give the failure path: NoSuchElementException, then an error state.
Show the production consequence of a failure that sticks: a transient error in a static final constant lasts as long as the class stays loaded, and only the first caller sees the cause. Put retries inside the function and log that first failure.
Weigh building on a surface that keeps moving: failure handling changed between JDK 26 and 27 without appearing in the JEP's change list, so read each release's API documentation. Decide whether a shared platform may depend on it before it is final.
## One lazy slot per element A **lazy constant** (`java.lang.LazyConstant`, a preview API at JDK 27) holds one value that a **computing function** produces on first use, at most once. The lazy collection factories apply that idea to many values. Each returns an unmodifiable collection whose shape is fixed at construction and whose contents are computed slot by slot, on first access: | Factory | Preview since | Function type | Fixed at construction | Computed on first access | |---|---|---|---|---| | `List.ofLazy(size, fn)` | 26 | `IntFunction` | The size | The element at that index | | `Map.ofLazy(keys, fn)` | 26 | `Function` | The keys, copied | The value for that key | | `Set.ofLazy(candidates, pred)` | 27 | `Predicate` | The candidates, copied | Whether that candidate is a member | The Javadoc says each can be thought of as backed by `LazyConstant`s, except that performance and storage efficiency might be better; the real implementation is the package-private `java.util.LazyCollections`, which keeps results in `@Stable` arrays. Elements are eligible for constant folding under the same rule as a single lazy constant, so these collections belong in `static final` fields when that matters. ## What triggers a computation Laziness is per slot, but not every method stays lazy: - **List:** `size()` and `isEmpty()` compute nothing, and `get(i)` computes only index `i`. - **Map:** `size()`, `containsKey()` and `keySet()` compute nothing, and `get()` with a key outside the set returns `null` without running the function. - **Set:** `contains()` with a non-candidate returns `false` without running the function, but `size()` computes every candidate, because it must count the members. At JDK 27 `isEmpty()` does too, because it is inherited as `size() == 0`. - **All three:** `equals()`, `hashCode()` and `toString()` may trigger initialization of one or more slots, unlike `LazyConstant.toString()`, which never does. So logging a lazy collection can run your function. ## When the computing function throws At JDK 27 every failure takes one path: 1. The first caller gets `NoSuchElementException` with the original as its **cause**. This covers runtime exceptions and errors alike. 2. That slot enters an **error state**. The function is never invoked for it again. 3. Threads that were blocked on it, and every later caller, get `NoSuchElementException` with **no cause**; the message names the original exception's class. 4. Other slots are unaffected: in a lazy list, a failure at index 1 leaves index 2 computable. Whole-collection methods that reach the failed slot do throw, such as `toString()` and `hashCode()` and, on a lazy set, `size()`. Only the class name is kept. A single constant stores it as a string in the private field `computingFunctionOrExceptionType` of the JDK-internal `LazyConstantImpl`, and a lazy collection in a `String[]` in its private `Throwables` class. The source comments give the reason: keeping the exception's class would pin its class loader. So only the first caller ever sees the original exception, and if that caller swallows it, the stack trace is gone. Two special cases go the same way. A function that returns `null` fails with a `NullPointerException` cause, so wrap nullable values in `Optional`. A function that re-enters the same constant, index, key or candidate gets an `IllegalStateException` at the inner call, and if it lets that escape, the slot fails with it as the cause. The judgment call is **transient failure**. A lazy constant in a `static final` field whose function threw on a network timeout stays failed for as long as that class stays loaded. Put any retry inside the function, or do not use a lazy constant for something that can fail temporarily. Failure also spreads through composition: a constant whose function calls a failed constant's `get()` fails too, unless it catches the exception. ## The same failures on earlier releases This is where the release matters most, and JEP 531's change list does not mention it; the difference shows in each release's API documentation. | Case | JDK 25 `StableValue` | JDK 26 `LazyConstant` | JDK 27 `LazyConstant` | |---|---|---|---| | Function throws | Rethrown, nothing recorded, may retry | Relayed, stays uninitialized, `get()` may retry | `NoSuchElementException`, never retried | | Function returns `null` | Allowed as content | `NullPointerException` | `NoSuchElementException` with that cause | | Function re-enters itself, uncaught | `IllegalStateException` | `IllegalStateException`, not initialized | `NoSuchElementException` with that cause | ## From `StableValue` to `LazyConstant` 1. **JDK 25, first preview (JEP 502).** `StableValue` was low-level: `StableValue.of()` plus `orElseSet`, `trySet` and `setOrThrow`, with factories such as `supplier`, `function`, `intFunction`, `list` and `map`. 2. **JDK 26, second preview (JEP 526).** Renamed `LazyConstant` to match the main use case. `orElseSet`, `setOrThrow` and `trySet` went, leaving factories that take a computing function; `function` and `intFunction` went too. Lists and maps moved to `List.ofLazy` and `Map.ofLazy`, and `null` results were disallowed. 3. **JDK 27, third preview (JEP 531).** `isInitialized` and `orElse` were removed because they could be used against the API's design goals, and `Set.ofLazy` was added. For migration, a `StableValue` set at its point of use, from something the caller knew, has no direct form now, because the function must exist at construction. JEP 531's Future Work names that gap. `LazyConstant` at 27 exposes only `get()`, `of()` and the `Object` methods, so the only hint of its state is `toString()`, a debugging string in an implementation-dependent format.
- How would you handle a computing function that can fail temporarily, such as a network call, at JDK 27?Retry inside the function, because a throw is final for that slot: the function never runs again and every later access gets `NoSuchElementException`. If retries can still fail and the program must recover later, a lazy constant is the wrong tool, so hold the value in something replaceable. Log the first failure too, since only that caller's exception carries the cause.
- Why does only the first caller see the original exception as the cause?The implementation keeps just the exception's class name, as an interned string, not the exception or its class. Source comments in `LazyConstantImpl` and `LazyCollections` say storing the class would pin its class loader. So later callers, including threads that were blocked during the computation, get a `NoSuchElementException` with no cause and a message naming that class.
- Why does a lazy set's size() run the computing function when a lazy list's size() does not?A lazy list's size is fixed at construction. A lazy set is defined by membership: its candidates are fixed, but which of them are members depends on the predicate, so counting members means computing every candidate's status. `isEmpty()` goes the same way at JDK 27, and if any candidate's computation fails, `size()` throws `NoSuchElementException`.
- What can't be replaced directly when migrating StableValue code written for JDK 25?Code calling `orElseSet` with a function chosen at the call site: `LazyConstant` takes its function at construction, so it must be known then. `trySet` and `setOrThrow` have no counterpart. `StableValue.list` and `map` become `List.ofLazy` and `Map.ofLazy`, and `function` and `intFunction` give way to those lazy collections, whose functions can no longer produce `null`.
- A failed lazy constant simply runs its function again on the next get() at JDK 27.
- At JDK 27 get() rethrows the computing function's own exception type to every caller.
- One failed index makes every get() on a lazy list throw.
- A lazy set's size() returns the candidate count without computing anything.
- Failure handling is the same on JDK 25, 26 and 27; only the names changed.
- StableValue still exists at JDK 27 as a lower-level alternative to LazyConstant.
- List.ofLazy
- not finalpre-release 26
- Map.ofLazy
- not finalpre-release 26
- Set.ofLazy
- not finalpre-release 27
- LazyConstant
- not finalpre-release 26
- StableValue
- pre-release 25removed 26
Assumes JDK 27, the third preview; failure handling differs on JDK 25 and 26, where a throwing function could be run again.
context
- JEP 531: Lazy Constants (Third Preview)openjdk.org
- List (Java SE 27 & JDK 27)docs.oracle.com
- LazyConstant (Java SE 26 & JDK 26)docs.oracle.com