00:00

Stable Values in Java 25 (Preview)

Last updated: · Preview in Java 25

A stable value holds data that is set at most once, for example a logger or a configuration object that is expensive to create. Unlike a final field, it can be initialised lazily, on first use, and the JIT can still treat it as a constant afterwards. Stable values are a preview API in Java 25 (JEP 502).

This tutorial covers StableValue.of with orElseSet, the stable supplier and list factories, and the API's status after Java 25.

1. Why Were Stable Values Proposed?

final fields must be assigned in the constructor, so expensive objects are created at start-up even if they are never used. Lazy alternatives, such as double-checked locking or holder classes, are verbose, easy to get wrong, and prevent the JIT from optimising the field as a constant. Stable values give lazy, thread-safe initialisation with the performance of a constant.

2. Syntax and Preview Flags

Syntax.java
private final StableValue<Logger> logger = StableValue.of();
Logger logger() {
    return logger.orElseSet(() -> createLogger());   // created on first call only
}

static final Supplier<Config> CONFIG = StableValue.supplier(Config::load);
static final List<Long> TABLE = StableValue.list(100, i -> compute(i));
Commands
javac --release 25 --enable-preview LazyLogger.java && java --enable-preview LazyLogger

3. Practical Examples

Example 1: A lazily created logger

LazyLogger.java
// Preview in Java 25 (JEP 502): compile and run with --enable-preview
public class LazyLogger {
    static class ExpensiveLogger {
        ExpensiveLogger() {
            System.out.println("  (creating logger: slow, happens once)");
        }
        void log(String msg) {
            System.out.println("  LOG " + msg);
        }
    }

    // A stable value: set at most once, then treated like a constant by the JIT
    private final StableValue<ExpensiveLogger> logger = StableValue.of();

    ExpensiveLogger logger() {
        return logger.orElseSet(ExpensiveLogger::new);   // lazy and thread-safe
    }

    public static void main(String[] args) {
        LazyLogger app = new LazyLogger();
        System.out.println("App started; logger set? " + app.logger.isSet());
        app.logger().log("first request");
        app.logger().log("second request");
        System.out.println("logger set? " + app.logger.isSet());
    }
}
Output
App started; logger set? false
  (creating logger: slow, happens once)
  LOG first request
  LOG second request
logger set? true

Compile and run: javac --release 25 --enable-preview LazyLogger.java && java --enable-preview LazyLogger

Example 2: Stable suppliers and lists

Each element of a stable list is computed the first time it is requested and then reused.

StableFactories.java
import java.util.List;
import java.util.function.IntFunction;
import java.util.function.Supplier;

// Preview in Java 25 (JEP 502): compile and run with --enable-preview
public class StableFactories {
    // A stable supplier computes its value on the first get() only
    static final Supplier<String> CONFIG = StableValue.supplier(() -> {
        System.out.println("  (reading configuration)");
        return "region=ap-south-1";
    });

    // A stable list computes each element on first access
    static final List<Long> FACTORIALS = StableValue.list(21, n -> {
        System.out.println("  (computing " + n + "!)");
        long f = 1;
        for (int i = 2; i <= n; i++) f *= i;
        return f;
    });

    public static void main(String[] args) {
        System.out.println(CONFIG.get());
        System.out.println(CONFIG.get());
        System.out.println("10! = " + FACTORIALS.get(10));
        System.out.println("10! = " + FACTORIALS.get(10));
        System.out.println("20! = " + FACTORIALS.get(20));
    }
}
Output
  (reading configuration)
region=ap-south-1
region=ap-south-1
  (computing 10!)
10! = 3628800
10! = 3628800
  (computing 20!)
20! = 2432902008176640000

Compile and run: javac --release 25 --enable-preview StableFactories.java && java --enable-preview StableFactories

4. States of a Stable Value

Stable value lifecycle A stable value starts unset. The first orElseSet call runs the supplier once, even when several threads call it at the same time, and stores the result. Later calls return the stored value, which the JIT can treat as a constant. unset nothing computed first orElseSet supplier runs once set value stored later calls constant-like reads
Figure 1: The value can change only once, from unset to set.

5. Status After Java 25

In Java 26 the API was renamed to Lazy Constants (JEP 526, second preview), and it continued as a preview in Java 27. Code using StableValue will need changes on newer JDKs.

6. Important Points and Best Practices

  • Use stable values for expensive, rarely changing objects: loggers, parsers, configuration, caches of computed tables.
  • The supplier runs at most once, even with concurrent callers.
  • Do not use preview APIs in production code; the API has already changed after Java 25.
  • Compile and run with --enable-preview.

7. Summary

  • Stable values are a preview API in Java 25 (JEP 502).
  • They hold a value set at most once, lazily and thread-safely.
  • orElseSet, StableValue.supplier and StableValue.list cover common cases.
  • Java 26 renamed the API to Lazy Constants (JEP 526).

Related Tutorials

8. References