Scoped Values in Java 21 (Preview)
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
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
javac --release 21 --enable-preview RequestContext.java && java --enable-preview RequestContext
3. Practical Examples
Example 1: Request context without parameters
// 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());
}
}
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
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());
}
}
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
5. Important Points and Best Practices
- Declare scoped values as
static finalfields, likeThreadLocals. - There is no
set()method: to change a value, rebind it for a nested scope. get()throwsNoSuchElementExceptionoutside a binding; check withisBound()or useorElse.- 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 withget(). - Values are immutable and removed automatically when the scope ends.
- Structured concurrency subtasks inherit bindings cheaply.
Related Tutorials
- Scoped Values (Java 25, Final)
- Structured Concurrency (Preview)
- Virtual Threads
- Multithreading in Java
7. References
Frequently Asked Questions (FAQ)
Q1. What is a scoped value in Java?
An immutable value bound for the duration of a method call and readable by all code called within it, without passing parameters. It was a preview in Java 21 and is final in Java 25.
Q2. How is ScopedValue different from ThreadLocal?
A scoped value is immutable, has a bounded lifetime and is cleaned up automatically. A ThreadLocal can be changed at any time and lives until it is removed.
Q3. Can a scoped value be changed?
Not directly. You can rebind it to a different value for a nested scope with another where(...).run(...).
Q4. Do child threads see scoped values?
Subtasks forked inside a StructuredTaskScope inherit the bindings. Threads started in other ways do not.