Scoped Values in 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
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
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"));
}
}
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
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");
}
}
}
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
5. ScopedValue vs ThreadLocal
| Aspect | ThreadLocal | ScopedValue |
|---|---|---|
| Change the value | set() at any time | only by rebinding in a nested scope |
| Lifetime | until remove() or thread end | exactly the run / call |
| Child threads | copy with InheritableThreadLocal | shared with structured-concurrency subtasks |
| Cost with many virtual threads | can be high | low |
6. Important Points and Best Practices
- Declare scoped values as
static finalfields. - Use them for read-only context such as the current user, tenant or transaction.
- Prefer
orElseorisBoundin code that may run outside a scope. - Keep
ThreadLocalfor 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(...)orcall(...). - Values are immutable, rebindable for nested scopes, and removed automatically.
- They are a safer, cheaper alternative to
ThreadLocalfor shared context.
Related Tutorials
- Scoped Values (Java 21 Preview)
- Structured Concurrency (Fifth Preview)
- Virtual Threads (Java 21)
- Multithreading in Java
8. References
Frequently Asked Questions (FAQ)
Q1. Are scoped values final in Java 25?
Yes. JEP 506 made them a standard feature in Java 25 after previews in Java 21 to 24.
Q2. What is the difference between ScopedValue and ThreadLocal?
A scoped value is immutable and lives only for the duration of a run or call. A ThreadLocal can be changed at any time and lives until it is removed.
Q3. Can a scoped value be read in another thread?
Only in subtasks forked inside a StructuredTaskScope, which inherit bindings. Ordinary executor threads do not see them.
Q4. What happens if get() is called outside a scope?
It throws NoSuchElementException. Use isBound() or orElse() to avoid that.