00:00

Scoped Values in Java 21 (Preview)

Last updated: · Preview in Java 21

A scoped value shares an immutable value with every method called inside a bounded block of code, without passing it as a parameter. In Java 21 scoped values are a preview API (JEP 446). They became final in Java 25 (JEP 506).

This tutorial shows how to bind and read a scoped value, how rebinding works, and why scoped values are safer and cheaper than ThreadLocal.

1. Why Were Scoped Values Added?

Frameworks often need per-request data, such as the current user, deep in the call stack. ThreadLocal is the traditional tool, but it is mutable, its value lives until someone calls remove(), and copying inheritable values into many child threads is costly. With millions of virtual threads these weaknesses matter. Scoped values are immutable, bound for a clearly defined scope, and efficiently shared with child tasks.

2. Syntax and Preview Flags

Syntax.java
static final ScopedValue<String> USER = ScopedValue.newInstance();

ScopedValue.where(USER, "asha").run(() -> service());     // bind for this call
String r = ScopedValue.where(USER, "asha").call(() -> load()); // with a result

USER.get();        // read anywhere inside the scope
USER.isBound();    // false outside any scope
Commands
javac --release 21 --enable-preview RequestContext.java && java --enable-preview RequestContext

3. Practical Examples

Example 1: Request context without parameters

RequestContext.java
// Preview in Java 21 (JEP 446): compile and run with --enable-preview
public class RequestContext {
    static final ScopedValue<String> USER = ScopedValue.newInstance();

    // Deep in the call chain: no user parameter needed
    static void audit(String action) {
        System.out.println("  audit: " + USER.get() + " -> " + action);
    }

    static void service() {
        audit("view invoice");
        ScopedValue.where(USER, "system").run(() -> audit("send reminder"));   // nested rebinding
        audit("download invoice");
    }

    public static void main(String[] args) {
        System.out.println("Request from asha:");
        ScopedValue.where(USER, "asha").run(RequestContext::service);
        System.out.println("Bound outside the scope? " + USER.isBound());
    }
}
Output
Request from asha:
  audit: asha -> view invoice
  audit: system -> send reminder
  audit: asha -> download invoice
Bound outside the scope? false

Compile and run: javac --release 21 --enable-preview RequestContext.java && java --enable-preview RequestContext

The nested where(USER, "system") rebinding applies only inside its own run; afterwards USER is "asha" again.

Example 2: Compared with ThreadLocal

ThreadLocalComparison.java
import java.util.concurrent.StructuredTaskScope;

// Preview in Java 21 (JEP 446 and JEP 453): compile and run with --enable-preview
public class ThreadLocalComparison {
    static final ThreadLocal<String> TL_TENANT = new ThreadLocal<>();
    static final ScopedValue<String> SV_TENANT = ScopedValue.newInstance();

    public static void main(String[] args) throws Exception {
        // ThreadLocal: mutable, and must be removed manually
        TL_TENANT.set("acme");
        TL_TENANT.set("globex");                       // anyone can overwrite it
        System.out.println("ThreadLocal value  : " + TL_TENANT.get());
        TL_TENANT.remove();                            // forget this and the value leaks

        // ScopedValue: immutable inside the scope, removed automatically
        String result = ScopedValue.where(SV_TENANT, "acme").call(() -> {
            // Child tasks of a structured scope inherit the binding
            try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
                var child = scope.fork(() -> "child sees " + SV_TENANT.get());
                scope.join().throwIfFailed();
                return child.get();
            }
        });
        System.out.println("ScopedValue result : " + result);
        System.out.println("After the scope    : bound = " + SV_TENANT.isBound());
    }
}
Output
ThreadLocal value  : globex
ScopedValue result : child sees acme
After the scope    : bound = false

Compile and run: javac --release 21 --enable-preview ThreadLocalComparison.java && java --enable-preview ThreadLocalComparison

Subtasks forked in a StructuredTaskScope inherit the binding automatically, without copying.

4. Lifetime of a Binding

Scope of a scoped value binding where binds a value, run or call executes code that can read it, nested where calls create temporary rebindings, and the binding disappears automatically when run returns. where(USER, "asha") create binding run(...) USER.get() works nested where temporary rebinding run returns binding removed
Figure 1: A scoped value is readable only during the call, and never needs manual cleanup.

5. Important Points and Best Practices

  • Declare scoped values as static final fields, like ThreadLocals.
  • There is no set() method: to change a value, rebind it for a nested scope.
  • get() throws NoSuchElementException outside a binding; check with isBound() or use orElse.
  • Preview status in Java 21 means compile and run with --enable-preview; the API was finalised with small changes in Java 25.

6. Summary

  • Scoped values are a preview API in Java 21 (JEP 446) and final in Java 25 (JEP 506).
  • Bind with ScopedValue.where(...).run(...) and read with get().
  • Values are immutable and removed automatically when the scope ends.
  • Structured concurrency subtasks inherit bindings cheaply.

Related Tutorials

7. References