00:00

Scoped Values in Java 25

Last updated: · Standard (Java 25)

A scoped value lets a method share an immutable value with all the code it calls, for a clearly bounded time, without passing it as a parameter. After four previews starting in Java 21, scoped values are final in Java 25 (JEP 506) and live in java.lang.ScopedValue.

This tutorial covers binding values, reading them, temporary rebinding, and the rules for threads.

1. Why Use Scoped Values?

Web and messaging frameworks need request data, such as the tenant or user, in many layers of code. Passing it through every method is clumsy, and ThreadLocal has drawbacks: any code can change the value, it stays until someone calls remove(), and inheriting it into child threads copies data. Scoped values are immutable, are removed automatically when the scope ends, and work well with millions of virtual threads.

2. Syntax

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

ScopedValue.where(TENANT, "acme").run(() -> service());          // no result
String r = ScopedValue.where(TENANT, "acme").call(() -> load()); // with a result
ScopedValue.where(A, a).where(B, b).run(...);                     // several bindings

TENANT.get();          // throws NoSuchElementException if not bound
TENANT.isBound();
TENANT.orElse("none");

3. Practical Examples

Example 1: Binding, calling and rebinding

TenantContext.java
public class TenantContext {
    static final ScopedValue<String> TENANT = ScopedValue.newInstance();
    static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();

    static String loadInvoices() {
        // Read the bound values anywhere inside the scope
        return "req " + REQUEST_ID.get() + ": invoices of " + TENANT.get();
    }

    public static void main(String[] args) throws Exception {
        // Bind two values at once; call() returns a result
        String result = ScopedValue.where(TENANT, "acme")
                .where(REQUEST_ID, 7)
                .call(TenantContext::loadInvoices);
        System.out.println(result);

        // run() for code without a result; nested where() rebinds temporarily
        ScopedValue.where(TENANT, "globex").where(REQUEST_ID, 8).run(() -> {
            System.out.println(loadInvoices());
            ScopedValue.where(TENANT, "audit").run(() -> System.out.println("  nested: " + loadInvoices()));
            System.out.println("  after nested: " + TENANT.get());
        });

        // Outside any binding
        System.out.println("bound? " + TENANT.isBound() + ", orElse: " + TENANT.orElse("none"));
    }
}
Output
req 7: invoices of acme
req 8: invoices of globex
  nested: req 8: invoices of audit
  after nested: globex
bound? false, orElse: none

The nested where(TENANT, "audit") changes the value only inside its own run. Afterwards TENANT is "globex" again.

Example 2: Bindings belong to the current thread

ScopeVsThreads.java
import java.util.NoSuchElementException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ScopeVsThreads {
    static final ScopedValue<String> USER = ScopedValue.newInstance();

    public static void main(String[] args) throws Exception {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            ScopedValue.where(USER, "asha").run(() -> {
                System.out.println("same thread sees: " + USER.get());
                // A thread started with an executor does NOT inherit the binding
                Future<Boolean> other = executor.submit(USER::isBound);
                try {
                    System.out.println("executor thread bound? " + other.get());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        try {
            USER.get();
        } catch (NoSuchElementException e) {
            System.out.println("get() outside a scope: NoSuchElementException");
        }
    }
}
Output
same thread sees: asha
executor thread bound? false
get() outside a scope: NoSuchElementException

A task submitted to an ordinary executor does not see the binding. Subtasks forked inside a StructuredTaskScope do inherit it, which is the recommended way to share context with child tasks.

4. How a Binding Lives and Ends

Lifetime of a scoped value binding where creates a binding, run or call executes code that can read it, a nested where temporarily rebinds it, and when run returns the binding is gone. where(TENANT, "acme") create binding run / call get() returns "acme" nested where temporary new value scope ends nothing to clean up
Figure 1: The binding has a clear start and end, and no remove() call is needed.

5. ScopedValue vs ThreadLocal

AspectThreadLocalScopedValue
Change the valueset() at any timeonly by rebinding in a nested scope
Lifetimeuntil remove() or thread endexactly the run / call
Child threadscopy with InheritableThreadLocalshared with structured-concurrency subtasks
Cost with many virtual threadscan be highlow

6. Important Points and Best Practices

  • Declare scoped values as static final fields.
  • Use them for read-only context such as the current user, tenant or transaction.
  • Prefer orElse or isBound in code that may run outside a scope.
  • Keep ThreadLocal for genuinely per-thread mutable caches, such as a reusable buffer.

7. Summary

  • Scoped values are final in Java 25 (JEP 506).
  • Bind with ScopedValue.where(...).run(...) or call(...).
  • Values are immutable, rebindable for nested scopes, and removed automatically.
  • They are a safer, cheaper alternative to ThreadLocal for shared context.

Related Tutorials

8. References