Scoped values
A scoped value passes data to code deep in a call chain without adding a parameter to every method. Unlike a ThreadLocal, the value exists only while a specific call runs and cannot be changed, so it can never leak into the next task on the same thread. This page explains the model behind scoped values, shows binding, nesting, inheritance by subtasks, exceptions and nulls, and compares their cost with ThreadLocal.
Contents
What a scoped value is
Server code often needs the current user, tenant or request ID in methods far from where the request arrived. Passing it as a parameter through every layer clutters every signature, including layers that never use it. The traditional alternative, ThreadLocal
- Unconstrained mutation: any code can call
at any time, so it is hard to know who changed a value.set - Unbounded lifetime: a value stays until
is called or the thread dies. In a thread pool, a forgottenremove() leaks the value into the next task.remove() - Expensive inheritance:
copies every value into each child thread, which costs memory when millions of virtual threads are created.InheritableThreadLocal
A ScopedValuestatic finalScopedValue.where(KEY, value).run(...).call(...)KEY.get()set
Underneath, each thread holds a reference to its current set of bindings. where(...).run(...)finallyStructuredTaskScopeget()
| JDK | JEP | Status |
|---|---|---|
| 20 | JEP 429 | Incubator module |
| 21 | JEP 446 | Preview |
| 22, 23, 24 | JEP 464, 481, 487 | Further previews; the static runWherecallWherecall |
| 25 | JEP 506 | Standard; orElsenull |
The examples were compiled and run on JDK 25. One of them also uses StructuredTaskScope--enable-preview
Binding a value for one call
In the program, the repository two levels down reads the current user without receiving it as a parameter. The same document ID is opened as "ana" and as "guest", so the service's access check gives two different results from the same code.
import java.util.NoSuchElementException;
public class RequestContext {
// One shared key; the value lives only inside a where(...).run(...) call
static final ScopedValue<String> USER = ScopedValue.newInstance();
// Deep in the call chain, no parameter carries the user
static class Repository {
String load(String id) {
return "doc " + id + " loaded for " + USER.get();
}
}
static class Service {
private final Repository repo = new Repository();
String open(String id) {
if (USER.get().equals("guest") && id.startsWith("private")) {
return "denied " + id + " for guest";
}
return repo.load(id);
}
}
public static void main(String[] args) {
Service service = new Service();
ScopedValue.where(USER, "ana").run(() -> {
System.out.println(service.open("private-7"));
});
String result = ScopedValue.where(USER, "guest").call(() -> service.open("private-7"));
System.out.println(result);
// Outside any binding the value does not exist
System.out.println("bound here? " + USER.isBound());
System.out.println("orElse: " + USER.orElse("nobody"));
try {
USER.get();
} catch (NoSuchElementException e) {
System.out.println("get() outside a binding: NoSuchElementException");
}
}
}
Output:
doc private-7 loaded for ana
denied private-7 for guest
bound here? false
orElse: nobody
get() outside a binding: NoSuchElementException
- "ana" got the document; "guest" was denied by
, which read the binding withService.open just as the repository did.USER.get() takes arun and returns nothing;Runnable returns the lambda's result, here the "denied" string.call- Outside the bindings,
is false,isBound() returns the fallback, andorElse("nobody") throwsget() .NoSuchElementException
Nested bindings
Code inside a binding can bind the same key again for a narrower call. The inner value applies only during that call, and the outer one returns automatically afterwards. The program binds a role and an indentation depth together by chaining where
public class Rebinding {
static final ScopedValue<String> ROLE = ScopedValue.newInstance();
static final ScopedValue<Integer> DEPTH = ScopedValue.newInstance();
static void log(String msg) {
System.out.println(" ".repeat(DEPTH.orElse(0)) + "[" + ROLE.get() + "] " + msg);
}
static void adminTask() {
log("running admin task");
}
public static void main(String[] args) {
// Two values bound at once with a chained where
ScopedValue.where(ROLE, "user").where(DEPTH, 0).run(() -> {
log("start");
// A nested binding shadows the outer one for the inner call only
ScopedValue.where(ROLE, "admin").where(DEPTH, 1).run(Rebinding::adminTask);
log("back to the outer binding");
});
}
}
Output:
[user] start
[admin] running admin task
[user] back to the outer binding
The admin task ran with role adminuser
No leaks between pooled tasks, no inheritance by plain threads
Thread pools reuse threads. The program runs two tasks on a single-thread pool, so both use the same thread. The first sets a ThreadLocal
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadsAndInheritance {
static final ScopedValue<String> TENANT = ScopedValue.newInstance();
static final ThreadLocal<String> TENANT_TL = new ThreadLocal<>();
public static void main(String[] args) throws Exception {
// A pool with one thread, so both tasks run on the same thread
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
pool.submit(() -> {
TENANT_TL.set("acme"); // forgot remove()
ScopedValue.where(TENANT, "acme").run(() -> { });
}).get();
pool.submit(() -> {
System.out.println("next task, ThreadLocal: " + TENANT_TL.get());
System.out.println("next task, ScopedValue bound: " + TENANT.isBound());
}).get();
}
// A thread started with new Thread does not inherit the binding
ScopedValue.where(TENANT, "acme").run(() -> {
Thread child = new Thread(() ->
System.out.println("plain child thread sees a binding: " + TENANT.isBound()));
child.start();
try {
child.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("parent thread still sees: " + TENANT.get());
});
}
}
Output:
next task, ThreadLocal: acme
next task, ScopedValue bound: false
plain child thread sees a binding: false
parent thread still sees: acme
- The second task found "acme" left in the
by the first. In a web server that is one customer's data showing up in another customer's request. The scoped value was unbound, as it should be, because its binding ended with the first task'sThreadLocal .run - A thread started with
did not see the parent's binding, while the parent still did. Plain threads and executor tasks can outlive the binding, so they do not inherit it. The same is true ofnew Thread andForkJoinPool tasks.CompletableFuture
Inheritance by structured subtasks
Subtasks forked inside a StructuredTaskScope
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
// Needs JDK 25 with --enable-preview: StructuredTaskScope is still a preview API
public class SubtaskInheritance {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
static String fetch(String what) {
// Runs in a separate virtual thread, yet sees the caller's binding
return what + " for " + REQUEST_ID.get() + " on a virtual thread: "
+ Thread.currentThread().isVirtual();
}
public static void main(String[] args) throws InterruptedException {
ScopedValue.where(REQUEST_ID, "req-17").run(() -> {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> user = scope.fork(() -> fetch("user"));
Subtask<String> orders = scope.fork(() -> fetch("orders"));
scope.join();
System.out.println(user.get());
System.out.println(orders.get());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Rebinding inside the scope owner is visible to forks made after it
ScopedValue.where(REQUEST_ID, "outer").run(() ->
ScopedValue.where(REQUEST_ID, "inner").run(() -> {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> s = scope.fork(() -> REQUEST_ID.get());
scope.join();
System.out.println("subtask sees the innermost binding: " + s.get());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
}
Output (JDK 25, compiled with --enable-preview --release 25--enable-preview
user for req-17 on a virtual thread: true
orders for req-17 on a virtual thread: true
subtask sees the innermost binding: inner
- Both subtasks ran on virtual threads, which is what
uses by default, and both read "req-17" without any code to pass it.StructuredTaskScope.open() - The subtask forked under the nested binding saw "inner", the binding in effect at the moment of
.fork - Nothing was copied to the child threads: they share the owner's immutable set of bindings. That is why scoped values suit designs with thousands of short subtasks. See
structured concurrency for the scope API.
Exceptions, mutable objects and null
Real code throws exceptions and binds objects. The program saves two rows inside bindings, where the second row is empty so saveIOExceptionnull
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ErrorsAndValues {
static final ScopedValue<String> TX = ScopedValue.newInstance();
static final ScopedValue<List<String>> AUDIT = ScopedValue.newInstance();
static String save(String row) throws IOException {
if (row.isEmpty()) {
throw new IOException("empty row in " + TX.get());
}
AUDIT.get().add(TX.get() + ": saved " + row);
return row.toUpperCase();
}
public static void main(String[] args) {
List<String> audit = new ArrayList<>();
// call() passes the checked exception through, typed as IOException
try {
String r = ScopedValue.where(TX, "tx-1").where(AUDIT, audit).call(() -> save("a"));
System.out.println("returned " + r);
ScopedValue.where(TX, "tx-2").where(AUDIT, audit).call(() -> save(""));
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
System.out.println("after the exception, TX bound: " + TX.isBound());
// The binding is immutable, but the object it refers to is not
System.out.println("audit list filled through the binding: " + audit);
// where() accepts null; get() then returns null and isBound() is true
ScopedValue.where(TX, null).run(() ->
System.out.println("bound to null: isBound=" + TX.isBound() + ", get=" + TX.get()));
// orElse(null) is rejected in Java 25
try {
TX.orElse(null);
} catch (NullPointerException e) {
System.out.println("orElse(null): NullPointerException");
}
}
}
Output:
returned A
IOException: empty row in tx-2
after the exception, TX bound: false
audit list filled through the binding: [tx-1: saved a]
bound to null: isBound=true, get=null
orElse(null): NullPointerException
passed thecall through with its real type, so a normalIOException works. Since Java 23 the lambda forcatch (IOException e) is acall , which declares the exception type; earlier previews wrapped it in a plainScopedValue.CallableOp that threwCallable .Exception- After the exception,
was no longer bound: the binding ends however the call ends.TX - The binding itself cannot change, but the list it refers to can: "tx-1: saved a" was added through
. Bind immutable objects when possible, especially when subtasks share the binding.AUDIT.get() is accepted:where(TX, null) is true andisBound() returnsget() .null , however, throwsorElse(null) in Java 25, which was the one API change made when the feature became final.NullPointerException
How fast are get() and binding?
The program reads a value 50 million times from a call 20 frames deep, once with a scoped value and once with a ThreadLocal
public class LookupSpeed {
static final ScopedValue<Integer> SV = ScopedValue.newInstance();
static final ThreadLocal<Integer> TL = new ThreadLocal<>();
// Reads the value N times from a call 20 frames deep
static long readScoped(int depth, int n) {
if (depth > 0) {
return readScoped(depth - 1, n);
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += SV.get();
}
return sum;
}
static long readThreadLocal(int depth, int n) {
if (depth > 0) {
return readThreadLocal(depth - 1, n);
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += TL.get();
}
return sum;
}
public static void main(String[] args) throws Exception {
int n = 50000000;
TL.set(1);
for (int round = 0; round < 2; round++) { // round 0 is warm-up
long bestSv = Long.MAX_VALUE;
long bestTl = Long.MAX_VALUE;
long sumSv = 0;
long sumTl = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
sumSv = ScopedValue.where(SV, 1).call(() -> readScoped(20, n));
bestSv = Math.min(bestSv, System.nanoTime() - t0);
t0 = System.nanoTime();
sumTl = readThreadLocal(20, n);
bestTl = Math.min(bestTl, System.nanoTime() - t0);
}
if (round == 1) {
System.out.printf("ScopedValue.get x %,d: sum %,d, best of 3 %,d ms%n", n,
sumSv, bestSv / 1000000);
System.out.printf("ThreadLocal.get x %,d: sum %,d, best of 3 %,d ms%n", n,
sumTl, bestTl / 1000000);
}
}
// Binding cost: a new binding per call
long t0 = System.nanoTime();
long total = 0;
for (int i = 0; i < 1000000; i++) {
total += ScopedValue.where(SV, i).call(SV::get);
}
System.out.printf("1,000,000 where(...).call(...): sum %,d, %,d ms%n", total,
(System.nanoTime() - t0) / 1000000);
}
}
Output:
ScopedValue.get x 50,000,000: sum 50,000,000, best of 3 40 ms
ThreadLocal.get x 50,000,000: sum 50,000,000, best of 3 57 ms
1,000,000 where(...).call(...): sum 499,999,500,000, 89 ms
- Both lookups cost around a nanosecond per read in this hot loop, with the scoped value no slower than the
, despite the 20 frames between the binding and the read. Numbers this small mean the JIT optimized both reads heavily, so in practice the lookup cost is not a reason to choose either one.ThreadLocal - A new binding with
cost well under a microsecond. Binding once per request or per operation is effectively free.where(...).call(...) - The real saving appears with many threads: a
keeps an entry in every thread's map, and anThreadLocal is copied into every child. Scoped values allocate nothing per thread.InheritableThreadLocal
ScopedValue or ThreadLocal?
ThreadLocal | ScopedValue | |
|---|---|---|
| Give it a value | set | Only by binding for a call |
| Lifetime | Until remove() | The duration of runcall |
| Leaks into the next pooled task | Possible | Not possible |
| Child threads | Copied by InheritableThreadLocal | Shared with structured subtasks, no copy |
| Memory with many virtual threads | One map entry per thread | Nothing per thread |
| Available | Java 1.2 | Java 25 (preview in 21 to 24) |
- Use
for context that belongs to a request or an operation: user, tenant, request ID, transaction, locale.ScopedValue - Keep
for per-thread caches of expensive, non-thread-safe objects, where the value is meant to live as long as the thread. TheThreadLocalThreadLocal page covers that use. - Keep passing a parameter when only one or two methods need the value; a hidden dependency is harder to test.
- Code that must run on Java 21 to 24 can use scoped values only with
, and the API differs between those versions.--enable-preview
Scoped values are designed to work with