Scoped values
suggest changeA scoped value (java.lang.ScopedValue, final in Java 25, JEP 506) lets a method share a value with every method it calls, directly or indirectly, without passing it as a parameter. A typical use is per-request context in a server: the current user, a request id, a tenant or a transaction. Until now this was done with ThreadLocal (see Using ThreadLocal and Basic ThreadLocal usage).
A scoped value differs from a ThreadLocal in three ways:
- Immutable: there is no
set(). A value is bound once, for the duration of a call. - Bounded lifetime: the binding exists only while the
runorcallmethod you started is executing. When that method returns or throws, the binding is gone. There is noremove()to forget. - Cheap to inherit: child threads created by a
StructuredTaskScopesee the parent's bindings without copying anything. That matters when you have millions of virtual threads.
Scoped values were previewed in Java 20 to 24 and are a standard API in Java 25, with no flags needed. Structured concurrency, which some examples below use for inheritance, is still a preview API in Java 25 and needs --enable-preview.
Binding and reading a value
Create a ScopedValue with ScopedValue.newInstance(), usually as a private static final field, then bind a value to it with ScopedValue.where(key, value) and run code with run(...):
public class Basics {
// usually a private static final field, like a ThreadLocal
private static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println("bound before: " + USER.isBound());
ScopedValue.where(USER, "alice").run(() -> handleRequest());
System.out.println("bound after: " + USER.isBound());
try {
USER.get();
} catch (java.util.NoSuchElementException e) {
System.out.println("get() outside: " + e);
}
}
static void handleRequest() {
System.out.println("handleRequest sees " + USER.get());
loadProfile();
}
static void loadProfile() {
// no parameter needed: the value is visible anywhere down the call stack
System.out.println("loadProfile sees " + USER.get());
}
}
bound before: false
handleRequest sees alice
loadProfile sees alice
bound after: false
get() outside: java.util.NoSuchElementException: ScopedValue not bound
The ScopedValue object is only a key. The binding belongs to the current thread and to the dynamic extent of the run call: handleRequest and everything it calls see "alice", while code running before or after the call sees nothing. Calling get() when the value is not bound throws NoSuchElementException.
Returning a result with call()
run takes a Runnable. To return a value, use call, which takes a ScopedValue.CallableOp<R, X>. Its call() method may throw a checked exception of type X, and Carrier.call rethrows that same type, so you don't need to wrap checked exceptions. To bind several values at once, chain where:
import java.io.IOException;
public class CallDemo {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
// call() returns the result of the operation
int length = ScopedValue.where(USER, "alice").call(() -> USER.get().length());
System.out.println("length: " + length);
// bind several values at once by chaining where()
String line = ScopedValue.where(USER, "bob")
.where(REQUEST_ID, "req-17")
.call(CallDemo::describe);
System.out.println(line);
// call() rethrows the operation's checked exception type
try {
ScopedValue.where(USER, "carol").call(CallDemo::readQuota);
} catch (IOException e) {
System.out.println("caught: " + e.getMessage());
}
}
static String describe() {
return REQUEST_ID.get() + " by " + USER.get();
}
static long readQuota() throws IOException {
throw new IOException("quota file missing for " + USER.get());
}
}
length: 5
req-17 by bob
caught: quota file missing for carol
ScopedValue.where returns a ScopedValue.Carrier, an immutable set of bindings. You can store a carrier in a variable and reuse it, and carrier.get(key) reads a value from the carrier itself without running anything.
Early previews had ScopedValue.runWhere, callWhere and getWhere shortcuts. They were removed before the API became final, so older articles that use them won't compile on Java 25.
Optional values: isBound, orElse and orElseThrow
Library code often can't be sure that its caller bound a value. Three methods handle that:
public class Defaults {
static final ScopedValue<String> LOCALE = ScopedValue.newInstance();
static final ScopedValue<String> TENANT = ScopedValue.newInstance();
public static void main(String[] args) {
greet();
ScopedValue.where(LOCALE, "es").run(Defaults::greet);
try {
billing();
} catch (IllegalStateException e) {
System.out.println("billing: " + e.getMessage());
}
ScopedValue.where(TENANT, "acme").run(Defaults::billing);
// null is a valid bound value
ScopedValue.where(TENANT, null).run(() ->
System.out.println("bound to null: isBound=" + TENANT.isBound() + ", get=" + TENANT.get()));
}
static void greet() {
String locale = LOCALE.orElse("en"); // default when not bound
System.out.println(locale.equals("es") ? "Hola" : "Hello");
}
static void billing() {
String tenant = TENANT.orElseThrow(() -> new IllegalStateException("no tenant bound"));
System.out.println("billing tenant " + tenant);
}
}
Hello
Hola
billing: no tenant bound
billing tenant acme
bound to null: isBound=true, get=null
isBound()tells you whether a value is bound in the current thread.orElse(other)returns the bound value orother. In Java 25othermust not be null:orElse(null)throwsNullPointerException. UseisBound()if you need a null fallback.orElseThrow(supplier)throws an exception of your choice instead ofNoSuchElementException. A clear message like "not inside a request" makes misuse much easier to debug.
A value can be bound to null. In that case isBound() is true and get() returns null.
Rebinding in a nested scope
There's no set(), but code can bind a new value for a nested call. The inner binding hides the outer one for the duration of the inner call, and the outer value comes back when the inner call ends:
public class Rebind {
static final ScopedValue<Integer> DEPTH = ScopedValue.newInstance();
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
System.out.println("outer: " + USER.get());
// run some code as a different user; the outer binding is hidden, not changed
ScopedValue.where(USER, "admin").run(() ->
System.out.println("inner: " + USER.get()));
System.out.println("outer again: " + USER.get());
});
walk(3);
}
// a common use: track recursion depth without a parameter
static void walk(int n) {
int depth = DEPTH.orElse(0);
System.out.println(" ".repeat(depth) + "level " + depth);
if (n > 1) {
ScopedValue.where(DEPTH, depth + 1).run(() -> walk(n - 1));
}
}
}
outer: alice
inner: admin
outer again: alice
level 0
level 1
level 2
This is how you'd run part of a request with elevated privileges. With a ThreadLocal you would save the old value, call set, and restore it in a finally block. With scoped values, the restore is automatic and can't be forgotten.
Immutability applies to the binding, not to the object. If you bind a mutable object, such as an ArrayList, callees can still change its contents. Prefer immutable values, such as records and List.of(...), so that the context can't be modified by code far down the stack.
Example: request context in a server
Here is a small request handler. handle builds a RequestContext record, binds it, and from then on the logger and the service layer read it without any context parameter. Each request runs in its own virtual thread, so three requests are handled at once and each sees only its own context:
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
record Request(String path, String authToken) {}
record RequestContext(String requestId, String user, boolean admin) {}
final class Context {
static final ScopedValue<RequestContext> CURRENT = ScopedValue.newInstance();
static RequestContext get() {
return CURRENT.orElseThrow(() -> new IllegalStateException("not inside a request"));
}
}
final class Log {
static void info(String msg) {
String prefix = Context.CURRENT.isBound()
? "[" + Context.CURRENT.get().requestId() + " " + Context.CURRENT.get().user() + "] "
: "[-] ";
System.out.println(prefix + msg);
}
}
class OrderService {
List<String> listOrders() {
Log.info("loading orders");
return List.of("order-1", "order-2");
}
void deleteAll() {
if (!Context.get().admin()) {
throw new SecurityException(Context.get().user() + " may not delete orders");
}
Log.info("deleted all orders");
}
}
public class Server {
static final Map<String, String> TOKENS = Map.of("t1", "alice", "t2", "bob", "t9", "root");
static final AtomicInteger NEXT_ID = new AtomicInteger(100);
static final OrderService orders = new OrderService();
static String handle(Request req) {
String user = TOKENS.getOrDefault(req.authToken(), "anonymous");
var ctx = new RequestContext("req-" + NEXT_ID.incrementAndGet(), user, user.equals("root"));
return ScopedValue.where(Context.CURRENT, ctx).call(() -> dispatch(req));
}
// nothing below takes the context as a parameter
static String dispatch(Request req) {
Log.info("GET " + req.path());
try {
return switch (req.path()) {
case "/orders" -> "200 " + orders.listOrders();
case "/orders/delete" -> { orders.deleteAll(); yield "200 deleted"; }
default -> "404";
};
} catch (SecurityException e) {
Log.info("denied: " + e.getMessage());
return "403";
}
}
public static void main(String[] args) throws Exception {
List<Request> requests = List.of(
new Request("/orders", "t1"),
new Request("/orders/delete", "t2"),
new Request("/orders/delete", "t9"));
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> results = requests.stream()
.map(r -> executor.submit(() -> handle(r)))
.toList();
for (Future<String> f : results) {
Log.info("response: " + f.get());
}
}
}
}
[req-102 alice] GET /orders
[req-102 alice] loading orders
[req-103 bob] GET /orders/delete
[req-101 root] GET /orders/delete
[-] response: 200 [order-1, order-2]
[req-101 root] deleted all orders
[req-103 bob] denied: bob may not delete orders
[-] response: 403
[-] response: 200 deleted
The order of lines changes from run to run because the requests run concurrently, but each log line always carries the right request id and user. The main thread has no binding, so its lines get the [-] prefix. In a real framework the where(...).call(...) is in one place, the request dispatcher or a filter, and application code only calls Context.get().
No leaks into the next task
A thread pool reuses threads, so a ThreadLocal that isn't removed is still set when the thread runs the next task. Code usually calls remove() in a finally block, and when someone forgets, one user's context leaks into another user's request. A scoped value can't leak, because the binding ends when run exits, whether it returns or throws:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Leak {
static final ThreadLocal<String> TL_USER = new ThreadLocal<>();
static final ScopedValue<String> SV_USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
// ThreadLocal: set, but an exception skips the cleanup
pool.submit(() -> {
TL_USER.set("alice");
ScopedValue.where(SV_USER, "alice").run(() -> {
throw new RuntimeException("request failed");
});
TL_USER.remove(); // never reached
return null;
});
// the next task on the same pooled thread
pool.submit(() -> System.out.println(
"next task: ThreadLocal=" + TL_USER.get() + ", ScopedValue bound=" + SV_USER.isBound())).get();
}
}
}
next task: ThreadLocal=alice, ScopedValue bound=false
Inheritance: new threads don't see bindings
Bindings belong to a thread. A thread started with Thread.ofVirtual().start(...) or a task submitted to an ExecutorService does not see the parent's scoped values. That is different from InheritableThreadLocal, which is copied into every new thread:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NoInherit {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final InheritableThreadLocal<String> ITL_USER = new InheritableThreadLocal<>();
public static void main(String[] args) throws Exception {
ITL_USER.set("alice");
ScopedValue.where(USER, "alice").run(() -> {
Thread t = Thread.ofVirtual().start(() -> System.out.println(
"new thread: scoped bound=" + USER.isBound() + ", inheritable=" + ITL_USER.get()));
join(t);
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
ex.submit(() -> System.out.println("executor task: scoped bound=" + USER.isBound()));
}
// pass it on explicitly by capturing the value and binding again
String user = USER.get();
Thread t2 = Thread.ofVirtual().start(() ->
ScopedValue.where(USER, user).run(() ->
System.out.println("rebound in new thread: " + USER.get())));
join(t2);
});
}
static void join(Thread t) {
try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}
new thread: scoped bound=false, inheritable=alice
executor task: scoped bound=false
rebound in new thread: alice
The reason is the bounded lifetime. A plain thread can outlive the run call that started it, and then it would see a binding that no longer exists. If you need the value in such a thread, read it and bind it again in that thread, as in the last part of the example.
Inheritance into StructuredTaskScope subtasks
Structured concurrency guarantees that all subtasks finish before the scope closes, so they can't outlive the binding. Subtasks forked in a StructuredTaskScope therefore inherit the scoped values bound in the owner thread when the scope was opened. Nothing is copied: the subtask threads share the parent's bindings.
StructuredTaskScope is a preview API in Java 25, so this example needs --enable-preview:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Structured {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
String page = ScopedValue.where(USER, "alice").call(Structured::dashboard);
System.out.println(page);
}
static String dashboard() throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> profile = scope.fork(() -> fetch("profile"));
Subtask<String> orders = scope.fork(() -> fetch("orders"));
scope.join();
return profile.get() + " | " + orders.get();
}
}
static String fetch(String what) {
// runs in a different virtual thread, yet sees the caller's binding
return what + " of " + USER.get() + " (virtual=" + Thread.currentThread().isVirtual() + ")";
}
}
$ javac --release 25 --enable-preview -d out Structured.java
Note: Structured.java uses preview features of Java SE 25.
Note: Recompile with -Xlint:preview for details.
$ java --enable-preview -cp out Structured
profile of alice (virtual=true) | orders of alice (virtual=true)
You can also run it directly from source with java --enable-preview Structured.java.
The scope checks that bindings and scopes are nested properly. You can rebind a value and open a nested scope inside the new binding. But forking into an existing scope while a newer binding is active would give the subtask bindings the scope's owner never had, so fork throws StructureViolationException:
import java.util.concurrent.StructureViolationException;
import java.util.concurrent.StructuredTaskScope;
public class Violation {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
ScopedValue.where(USER, "alice").call(() -> {
try (var scope = StructuredTaskScope.open()) {
// OK: rebinding and opening a nested scope inside it
ScopedValue.where(USER, "admin").call(() -> {
try (var inner = StructuredTaskScope.open()) {
var s = inner.fork(() -> USER.get());
inner.join();
System.out.println("nested scope sees " + s.get());
}
return null;
});
// wrong: forking into the outer scope while a newer binding is active
ScopedValue.where(USER, "admin").run(() -> {
try {
scope.fork(() -> USER.get());
} catch (StructureViolationException e) {
System.out.println("fork failed: " + e.getClass().getSimpleName());
}
});
scope.join();
}
return null;
});
}
}
nested scope sees admin
fork failed: StructureViolationException
Cost with many threads
An InheritableThreadLocal is copied: every new thread gets its own map holding every inheritable value of its parent. With a few values this is cheap, but the cost grows with each value and is paid by every thread, which adds up with hundreds of thousands of virtual threads. Subtasks of a StructuredTaskScope only keep a reference to the parent's bindings, so the cost per thread doesn't depend on how many values are bound.
This program starts 100,000 virtual threads that all block, once with N inheritable thread-locals set in the parent and once with N scoped values inherited through a scope, and measures heap use per thread:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.StructuredTaskScope;
public class Footprint {
static final int THREADS = 100_000;
static final int VALUES = Integer.getInteger("values", 10);
static final List<InheritableThreadLocal<String>> LOCALS = new ArrayList<>();
static final List<ScopedValue<String>> SCOPED = new ArrayList<>();
static {
for (int i = 0; i < VALUES; i++) {
LOCALS.add(new InheritableThreadLocal<>());
SCOPED.add(ScopedValue.newInstance());
}
}
public static void main(String[] args) throws Exception {
if (args[0].equals("threadlocal")) {
measure("InheritableThreadLocal", (started, release) -> {
for (var tl : LOCALS) tl.set("value");
forkThreads(started, release);
});
} else {
measure("ScopedValue", (started, release) -> {
ScopedValue.Carrier carrier = ScopedValue.where(SCOPED.get(0), "value");
for (int i = 1; i < VALUES; i++) carrier = carrier.where(SCOPED.get(i), "value");
carrier.call(() -> { forkSubtasks(started, release); return null; });
});
}
}
interface Body { void run(CountDownLatch started, CountDownLatch release) throws Exception; }
static void measure(String label, Body body) throws Exception {
CountDownLatch started = new CountDownLatch(THREADS);
CountDownLatch release = new CountDownLatch(1);
Thread driver = Thread.ofPlatform().start(() -> {
try { body.run(started, release); } catch (Exception e) { throw new RuntimeException(e); }
});
System.gc();
long before = used();
long t0 = System.nanoTime();
started.await(); // all threads are running and blocked
long ms = (System.nanoTime() - t0) / 1_000_000;
System.gc();
long after = used();
System.out.printf("%-23s %,d threads started in %4d ms, %,6d bytes per thread%n",
label, THREADS, ms, (after - before) / THREADS);
release.countDown();
driver.join();
}
static void task(CountDownLatch started, CountDownLatch release) throws InterruptedException {
String v = LOCALS.get(VALUES - 1).get() != null ? LOCALS.get(VALUES - 1).get() : SCOPED.get(VALUES - 1).get();
if (!v.equals("value")) throw new AssertionError();
started.countDown();
release.await();
}
static void forkThreads(CountDownLatch started, CountDownLatch release) throws Exception {
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < THREADS; i++) {
threads.add(Thread.ofVirtual().start(() -> {
try { task(started, release); } catch (InterruptedException e) { }
}));
}
for (Thread t : threads) t.join();
}
static void forkSubtasks(CountDownLatch started, CountDownLatch release) throws Exception {
try (var scope = StructuredTaskScope.open()) {
for (int i = 0; i < THREADS; i++) {
scope.fork(() -> { task(started, release); return null; });
}
scope.join();
}
}
static long used() {
Runtime rt = Runtime.getRuntime();
return rt.totalMemory() - rt.freeMemory();
}
}
$ java -Dvalues=1 --enable-preview Footprint.java threadlocal
InheritableThreadLocal 100,000 threads started in 309 ms, 1,058 bytes per thread
$ java -Dvalues=1 --enable-preview Footprint.java scoped
ScopedValue 100,000 threads started in 307 ms, 1,172 bytes per thread
$ java -Dvalues=50 --enable-preview Footprint.java threadlocal
InheritableThreadLocal 100,000 threads started in 539 ms, 2,984 bytes per thread
$ java -Dvalues=50 --enable-preview Footprint.java scoped
ScopedValue 100,000 threads started in 383 ms, 1,138 bytes per thread
The numbers are noisy (they include the virtual thread itself and, for scoped values, the Subtask object), but the trend is clear. With one value the two are about the same. With 50 values each thread carries about 2 KB of copied thread-locals, while the scoped-value threads cost the same as before. Reads are cheap too: the JVM caches recently used bindings per thread, and JEP 506 aims for reading a scoped value to be about as fast as reading a local variable.
ScopedValue or ThreadLocal?
ThreadLocal |
ScopedValue |
|
|---|---|---|
| Change the value | set() at any time |
only by rebinding for a nested call |
| Lifetime | until remove() or thread exit |
the run/call method |
| Cleanup | manual, easy to forget in pools | automatic |
| Child threads | InheritableThreadLocal copies values |
StructuredTaskScope subtasks share them |
| Available since | Java 1.2 | Java 25 |
Use a scoped value for context that flows one way, from a caller down to its callees: user, request id, locale, tracing span, transaction. Keep ThreadLocal when:
- Code needs to change the value and have the change seen by later code on the same thread, for example a framework that sets state in one callback and reads it in another one.
- The value has no natural scope, such as a per-thread cache of an expensive object. Note that with virtual threads such caches don't work well anyway, see Virtual threads.
- You must support Java versions before 25.
Migrating usually means replacing a set(...) / try / finally remove() sequence at the entry point with a single ScopedValue.where(...).run(...), and replacing get() calls in callees with get(), orElse or orElseThrow on the scoped value. If some code calls set() in the middle of a request, turn that into a nested rebinding around the code that needs the new value.
Summary
- Create a key with
ScopedValue.newInstance()and bind it withScopedValue.where(key, value).run(...)or.call(...). Chainwhereto bind several values. - Every method called inside
run/callcan read the value withget(). Outside,get()throwsNoSuchElementException; useisBound(),orElse(non-null default) ororElseThrowwhen the value may be missing. - Values can't be changed, only rebound for a nested call. The binding ends automatically, so it can't leak into the next task on a pooled thread.
- Plain threads and executor tasks don't inherit bindings. Subtasks of a
StructuredTaskScope(preview in Java 25) do, without copying. - Scoped values are final in Java 25 and are the recommended replacement for
ThreadLocalwhen passing context to code you call.