ScopedValue in Java: Binding Context With where(), run() and call()
The Java 25 ScopedValue API: newInstance, where, run and call, get, isBound, orElse and orElseThrow. Dynamic scope, automatic rebinding in nested code, cleanup on exceptions, reusable carriers, null handling, and why plain threads don't inherit bindings.
kvi5hnuCode Sprout team member7 min readOn this page
A scoped value is a variable whose value is bound for the duration of one method call, and visible to everything that call does, at any depth, on the same thread. It solves the problems of articles 38 and 39 by design:
- A binding can't be changed. There's no
set(). Code that needs a different value creates a nested binding. - A binding ends automatically when the call that made it returns or throws. There's no
remove(). - Nested bindings restore the outer value when they end.
- Bindings are shared without copying with subtasks of a
StructuredTaskScope(article 41).
java.lang.ScopedValue is final in Java 25 (JEP 506) and needs no flags.
The API
private static final ScopedValue<RequestContext> CURRENT = ScopedValue.newInstance();
ScopedValue.where(CURRENT, ctx).run(() -> handle(request)); // bind, then run code
Quote q = ScopedValue.where(CURRENT, ctx).call(() -> price(trip)); // bind, run code, return a result
RequestContext c = CURRENT.get(); // inside: the bound value; outside: NoSuchElementException
| Method | What it does |
|---|---|
ScopedValue.newInstance() | creates a key. There's no public constructor. Keys are usually static final fields. |
ScopedValue.where(key, value) | returns a Carrier, a set of bindings that isn't active yet |
carrier.where(key2, value2) | adds another binding to the carrier |
carrier.run(Runnable) | binds everything in the carrier, runs the code, then unbinds |
carrier.call(CallableOp) | the same, but returns the code's result and passes its checked exception through |
carrier.get(key) | the value this carrier would bind, without binding it |
key.get() | the current binding, or NoSuchElementException |
key.isBound() | whether there's a binding now |
key.orElse(other) | the binding, or other (which must not be null) |
key.orElseThrow(supplier) | the binding, or throws the supplied exception |
The API in action
The program rebuilds the request context from article 38 on a scoped value, and runs through the API.
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Solution {
record RequestContext(String traceId, String tenant, String currency) {}
/** The framework's holder: private key, public read-only accessor. */
static final class Context {
private static final ScopedValue<RequestContext> CURRENT = ScopedValue.newInstance();
static ScopedValue.Carrier with(RequestContext ctx) {
return ScopedValue.where(CURRENT, ctx);
}
static RequestContext current() {
return CURRENT.orElseThrow(() -> new IllegalStateException("no request context"));
}
static boolean active() {
return CURRENT.isBound();
}
}
static final ScopedValue<String> ROLE = ScopedValue.newInstance();
static String format(int amount) {
return amount + " " + Context.current().currency();
}
static String describe() {
return Context.current().traceId() + " as " + ROLE.orElse("user");
}
static int loadFare(String route) throws IOException {
if (route.isEmpty()) throw new IOException("empty route");
return route.length() * 37;
}
public static void main(String[] args) throws Exception {
var lisbon = new RequestContext("t-101", "acme", "EUR");
var oslo = new RequestContext("t-102", "globex", "NOK");
// 1. Unbound: get() throws, isBound() and orElse() let code check first
System.out.println("1. active: " + Context.active() + ", role: " + ROLE.orElse("user"));
try {
ROLE.get();
} catch (NoSuchElementException e) {
System.out.println(" ROLE.get(): " + e.getMessage());
}
// 2. run(): bound for the duration of the call, and only then
Context.with(lisbon).run(() -> System.out.println("2. inside run: " + format(284)));
System.out.println(" after run, active: " + Context.active());
// 3. call(): returns a value and passes checked exceptions through
int fare = Context.with(lisbon).call(() -> loadFare("LIS-OSL"));
System.out.println("3. call returned " + fare);
try {
Context.with(lisbon).call(() -> loadFare(""));
} catch (IOException e) {
System.out.println(" call threw IOException: " + e.getMessage());
}
// 4. Several bindings at once
Context.with(oslo).where(ROLE, "agent").run(() -> System.out.println("4. " + describe()));
// 5. Rebinding in nested code: the outer binding comes back by itself
Context.with(lisbon).run(() -> {
String inner = Context.with(oslo).where(ROLE, "admin").call(Solution::describe);
System.out.println("5. inner: " + inner + "; then outer: " + describe());
});
// 6. Cleanup happens even when the code throws
try {
Context.with(lisbon).run(() -> { throw new IllegalArgumentException("bad dates"); });
} catch (IllegalArgumentException e) {
System.out.println("6. after exception, active: " + Context.active());
}
// 7. A carrier can be kept and reused; it doesn't bind anything by itself
ScopedValue.Carrier asAuditor = ScopedValue.where(ROLE, "auditor");
System.out.println("7. carrier holds " + asAuditor.get(ROLE) + ", ROLE bound now: " + ROLE.isBound());
Context.with(oslo).run(() -> asAuditor.run(() -> System.out.println(" " + describe())));
// 8. Plain threads and executors don't inherit bindings
Context.with(lisbon).run(() -> {
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
System.out.println("8. executor task active: " + pool.submit(Context::active).get());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
}
Output:
1. active: false, role: user
ROLE.get(): ScopedValue not bound
2. inside run: 284 EUR
after run, active: false
3. call returned 259
call threw IOException: empty route
4. t-102 as agent
5. inner: t-102 as admin; then outer: t-101 as user
6. after exception, active: false
7. carrier holds auditor, ROLE bound now: false
t-102 as auditor
8. executor task active: false
1. Unbound values
Outside any binding, get() throws NoSuchElementException ("ScopedValue not bound"). That's stricter than ThreadLocal.get(), which returns null and leaves you guessing whether the value was never set or was set to null. Code that can legitimately run without a binding checks with isBound(), or uses orElse or orElseThrow. Context.current() uses orElseThrow to turn a missing context into a clear framework error.
2. Dynamic scope
run binds the value, runs the lambda, and unbinds. During the call, format saw the context without receiving it as a parameter, and so would any method format called. That's dynamic scope: visibility follows the call chain at run time, not the curly braces in the source. After run returned, the context was gone.

3. Returning results, and checked exceptions
call returns the lambda's result. Its parameter is a ScopedValue.CallableOp<T, X extends Throwable>, so the compiler infers the exception type: loadFare throws IOException, so call throws IOException, and the catch received it unwrapped. There's no wrapping in ExecutionException or RuntimeException.
4. Several values
where chains: Context.with(oslo).where(ROLE, "agent") binds both values for one call. Keep separate keys for independent concerns (context, role, locale) rather than one big mutable holder object.
5. Rebinding
Inside the Lisbon request, a nested call bound Oslo and admin. The nested code saw them, and when it returned, the outer code saw Lisbon and user again. Compare that with article 38's thread-local runWith, whose nested remove() wiped the outer context. Here nesting is correct without any save-and-restore code. Rebinding is how you express "run this part as administrator", "use this transaction", or "one level deeper".
6. Exceptions
The lambda threw, and the binding was still removed. Cleanup is part of run and call, so it can't be forgotten.
7. Carriers
ScopedValue.where(...) only describes bindings. Nothing was bound until run was called, and the same carrier can be used many times. A framework can build a carrier once per request and run several pieces of code with it.
8. No inheritance by plain threads
A task submitted to an executor ran with no binding, even though it was submitted from inside run. Neither platform nor virtual threads started directly, nor executor tasks, inherit scoped values. Only subtasks of a StructuredTaskScope do, because the scope guarantees they finish before the binding ends (article 41). To pass context to an unstructured task, capture the value and bind it again inside the task:
RequestContext ctx = Context.current();
pool.submit(() -> Context.with(ctx).call(() -> work()));
Values must be immutable
A scoped value can't be rebound in place, but the object it refers to can still be mutable. Bind immutable values: records, List.copyOf, strings and numbers. If a subtask could change a bound HashMap, the immutability guarantee would be lost, and you'd have a data race (article 34). When code needs to accumulate results, return them, or bind a thread-safe collector object deliberately.
Null
where(key, null) is allowed: the key is then bound, isBound() is true, and get() returns null. orElse(null) throws NullPointerException in Java 25. Use isBound() when you need to distinguish "unbound" from a value.
What's current
ScopedValuewas an incubator API in Java 20 (JEP 429), a preview in Java 21 to 24 (JEPs 446, 464, 481, 487), and became final in Java 25 (JEP 506). Java 26 and 27 have the same API.- Java 23 changed
callto take aCallableOp, so checked exceptions pass through. Java 24 removed the staticrunWhereandcallWhereshortcuts, leaving only the fluentwhere(...).run(...)form. Java 25 madeorElse(null)an error. - Older articles show
ScopedValue.runWhere(KEY, value, op)orgetWhere. Those methods no longer exist.
Common questions
How do I change a scoped value?
You don't. Bind a new value for a nested call with where(...).run(...). Code that needs a value that changes over time, such as a counter, should hold it in a local variable or a thread-safe object, or rebind for each step (article 41 shows a depth counter built that way).
Is get() fast?
Yes. It's designed to be cheap enough to call in hot paths: the JDK caches recently used bindings for each thread, so repeated reads of the same scoped value don't search the bindings again.
Can I keep a scoped value in an instance field?
Yes, but the usual pattern is private static final, with a small public accessor. The key works as a capability: only code that can see the field can bind it or read it, and making it private keeps others from rebinding it.
What does ScopedValue.where(KEY, v) do without run or call?
Nothing visible. It returns a carrier, and bindings take effect only inside run or call.
Summary
- A scoped value is bound for exactly the duration of
runorcall, and visible to all code called from there on the same thread. It can't be set, and it unbinds itself, even on exceptions. get()throws when unbound. UseisBound(),orElseororElseThrowfor optional context.- Nested
where(...).run(...)rebinds a value, and the outer value returns automatically. callreturns results and passes checked exceptions through. Carriers can be reused.- Plain threads and executor tasks don't inherit bindings. Structured subtasks do (article 41). Bind only immutable values.
Practice questions
What does this print?
static final ScopedValue<String> USER = ScopedValue.newInstance();
static void show() { System.out.print(USER.orElse("none") + " "); }
ScopedValue.where(USER, "ana").run(() -> {
show();
ScopedValue.where(USER, "root").run(Main::show);
show();
});
show();
Answer
ana root ana none. The nested binding is visible only during the inner run. Then ana is visible again, and outside the outer run, USER is unbound, so orElse returns none.
A method needs a scoped value that may legitimately be unbound (a background job has no user). Which methods would you use, and which should you avoid?
Answer
Use isBound() or orElse(default), or orElseThrow with a clear exception where a binding is actually required. Avoid a bare get() on optional paths, because it throws NoSuchElementException when nothing is bound.
Inside ScopedValue.where(CTX, ctx).run(...), code calls executor.submit(() -> audit()), and audit reads CTX.get(). What happens, and how do you fix it?
Answer
The task runs on another thread, which has no binding, so CTX.get() throws NoSuchElementException. Capture the value first and rebind it inside the task: var c = CTX.get(); executor.submit(() -> ScopedValue.where(CTX, c).run(this::audit));. Better still, use a StructuredTaskScope, whose subtasks inherit bindings automatically.
Previous: The Problems With ThreadLocal in Java: Mutability, Leaks and InheritableThreadLocal
Next: Scoped Values With Structured Concurrency: Inheritance, Use Cases and Migrating From ThreadLocal

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.