Lesson · Virtual Threads & Structured Concurrency
Scoped values: context that ends where its block ends
15 min readScoped Values
A scoped value is a read-only binding for the duration of a block: code the block calls can read it, child threads it starts can read it, and everything outside sees nothing. There is no set and no remove, because where(...).run(...) establishes the binding and the end of that call is the cleanup, exception paths included. This lesson covers the shape, the inheritance rules, what rebinding really does, and the cases where a ThreadLocal is still the right answer.
The problem: ambient context with no end in sight
ThreadLocal solved the original problem, which is real: context has to reach code that never declared it. A framework knows the user and the tenant, application code calls back into the framework three layers down, and passing a parameter through every intermediate method is a tax on signatures that have nothing to do with the data.
The tool brought three flaws along with the solution. It is mutable from anywhere, so any layer can replace what the caller established. Its lifetime is the thread, not the request, so nothing in the code says when the value stopped being true. And inheritance copies, which turns per-thread memory into per-thread-key memory the moment there are child threads.
Look at the flow, not the storage. Request context is one-way: the caller knows it, the callees read it. A two-way channel is more machinery than that flow needs, and the missing piece is a way to say how long the value is true. A scoped value is exactly that statement.
// The ThreadLocal shape: write here, read far away, and remember the cleanup. static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>(); void serve(Request request) { CURRENT_USER.set(authenticate(request)); // depth 0 handle(request); // depth 1..n, reads it somewhere CURRENT_USER.remove(); // easy to skip, and every skip is invisible }
A ThreadLocal answers which thread; the real question is how long the value is true, and who is allowed to write it.
The shape: where(...) binds, run(...) scopes
A scoped value is declared once, typically as a private static final field, and created by newInstance(). It holds nothing until code binds it: where(CURRENT, context) returns a Carrier, and calling run on that Carrier executes the lambda with the binding in effect.
Inside the block, CURRENT.get() returns the value; after the call returns, the value is no longer bound and get() throws NoSuchElementException. The revert happens on the way out through every path, exceptions included, which is the entire cleanup story: there is no remove() to forget because there is no remove().
call() is the value-returning form and can throw checked exceptions; run() is for work that returns nothing. When several values belong together, chain the bindings or bind one immutable record: get() is fast because of a small per-thread cache, and the API is designed for a handful of scoped values rather than hundreds.
| Member | What it does | Notes |
|---|---|---|
| newInstance() | creates a scoped value that is unbound for every thread | one static final field per context slot |
| where(key, value) | starts a Carrier with one mapping | chainable: where(a, 1).where(b, 2) |
| run(Runnable) / call(CallableOp) | executes the operation with the mappings bound | restores the previous state on normal or exceptional exit |
| get() | reads the binding for the current thread | throws NoSuchElementException when nothing is bound |
| isBound() | reports whether a binding is in effect for this thread | useful for re-entrancy checks deep in a call chain |
| orElse(v) / orElseThrow(s) | fallbacks for a binding that may be absent | model optional context explicitly instead of catching |
The lifetime is the cleanup: whatever run() called, the binding ends when run() returns.
The dynamic scope is a bracket
inside reads · outside throws · children inherit by reference
where(CURRENT, ctx).run( ... )
A · serve
opens the scope; the binding starts here
B · handle
mid-chain; nothing declares the context
C · read
CURRENT.get() returns the bound value here
ThreadLocal · the comparison
A scoped value trades all four for one property: the binding exists only while the block that created it runs.
Inheritance: children read the same binding
A scoped value reaches child threads, not by copying but by reference: threads started inside the bound period inherit the bindings that are in effect. StructuredTaskScope goes a step further and captures the owner's bindings when the scope is created, so every subtask forked in it reads the same values.
That is what makes the pairing work in server code. The request thread binds the context, the handler forks subtasks, and the subtasks read the same context while writing their own results. A child must finish before the binding does, which the scope guarantees by construction, so the value cannot outlive its meaning.
Two limits belong in the same breath. A thread that already existed when the binding began inherits nothing, so pooled workers are not covered, and the JDK notes that legacy pools such as ForkJoinPool cannot support this because a forked child could outlive the parent's scope. And sharing by reference means sharing one object: the value must be immutable, or every access to it must be synchronized.
Inheritance by reference is why this scales: a hundred thousand child threads share one binding instead of holding a copy each.
Try it: the call chain, the rebind, and the child thread
The lab runs the same context through four scenes in both mechanisms: a call chain A to B to C that reads at C, a nested rebind, a child thread, and a read after the scope has ended. Switch the mechanism and watch what changes, including which mistakes fail loudly and which fail silently.
A read after the block is a loud error with a scoped value and a stale value with a ThreadLocal; pick which failure you want to debug.
Scoped value lab · one context, two mechanisms
pick a mechanism and a scenescene 1 · set above, read three layers down
where(CURRENT, ctx).run( ... )A · serve
opens the scope with where(...).run
B · handle
calls down; inside the binding
C · read
CURRENT.get() sees the context
serve() calls where(CURRENT, context).run(this::handle).
A calls B calls C; the binding is in effect for everything the lambda calls.
C reads CURRENT.get() and gets the context.
run() returns: the binding is gone, and no line of cleanup had to be written.
verdict
the end is visible in the code
The binding is bounded by the run call, exception paths included. Nothing outside the lambda can read it, and there is no remove() to forget because nothing was stored on the thread to remove.
Rebinding is legal; reading outside is not
A bound scoped value can be rebound for a nested scope: call where on the same key inside the block, and the callees of that inner call see the new value while the code that opened the outer binding still sees its own. When the nested call returns, the previous value is in effect again.
This is documented behaviour, not a loophole, and it is what makes scoped values usable for recursion counters, nested transactions and re-entrant framework calls: an inner layer adjusts what its callees see without touching what it sees itself. Rebinding never changes the binding of the code doing the writing, only of the code it calls.
The line that is not allowed is reading when nothing is bound: get() throws NoSuchElementException. Where absence is a normal state, isBound() answers the question directly, and orElse() or orElseThrow() models it as a value rather than an exception.
void foo() { ScopedValue.where(LEVEL, 1).run(this::bar); // outer binding } void bar() { LOG.info("depth " + LEVEL.get()); // 1 ScopedValue.where(LEVEL, LEVEL.get() + 1).run(this::baz); // nested rebind LOG.info("depth " + LEVEL.get()); // 1 again: the nested scope is gone } void baz() { LOG.info("depth " + LEVEL.get()); // 2 }
Rebinding changes what your callees see, never what you see.
Scoped values and ThreadLocals, field by field
The honest comparison is short, and the sharper part is at the end: the cases where the older tool still wins.
| Property | ThreadLocal | ScopedValue |
|---|---|---|
| Mutability | set() from any code that can reach the field | bound once per scope; readers cannot write |
| Lifetime | until remove(), or thread death | until the run or call returns |
| Cleanup | manual, and skippable on any exit path | automatic, exception-safe |
| Inheritance | InheritableThreadLocal copies the parent's map at thread creation | child threads read the same binding; nothing is copied |
| Cost at scale | a map entry on every live thread per key | a binding on the scope plus a cached per-thread pointer |
| Status | since Java 1.2 | incubator in JDK 20, preview in 21 to 24, final in JDK 25 |
- Two-way flows: a callee that publishes state back to a faraway caller cannot use a scoped value; the direction of the API is against it.
- Per-thread caches: expensive mutable objects a thread builds and reuses are caches rather than context; keep the ThreadLocal, or replace the object with an immutable shared one.
- Unstructured lifetimes: if no block owns the work, there is no scope to bind to, and a ThreadLocal is the mechanism that fits.
Migrate the one-way, immutable context; leave caches and two-way channels where they are.
Remember
Four sentences carry the whole API.
- Read-only by construction: no set(), so a faraway callee cannot rewrite what the caller established.
- Bounded by the block: where(...).run(...) binds and restores, on normal and exceptional exits alike.
- Inherited by reference by structured children: no map copies, and no child outlives the binding under a scope.
- Rebinding nests legally; reading outside throws: the inner scope changes what its callees see, and get() with nothing bound is a NoSuchElementException.
A ScopedValue ends where its lambda ends: the lifetime is the cleanup.
The context that crossed threads as a reference
A team replaced a request ThreadLocal with a scoped value and forked two subtasks in a scope. Both subtasks read the same context object, which was still the mutable class from before, and one subtask wrote its scratch field into it while the other read the half-updated value. The binding was read-only; the object inside it was not. A scoped value shares one instance with every child thread, so it demands immutability in a way that per-thread copies used to hide: the copies made mutation visible only to the writer, and the sharing removed that accident. Make the context a record, or protect the access, before you share it.
Interview angles
What is a scoped value?+
A read-only binding of a value to a block: the code the block calls, and the child threads it starts, can read it; code outside sees nothing, and the binding is gone when the block returns.
How is it better than a ThreadLocal for request context?+
There is no set() for a faraway callee to abuse, no remove() to forget, and inheritance is by reference rather than a copied map. The lifetime is visible in the code because it is exactly the run() or call() invocation.
The direction and the lifetime are the differences: a scoped value is written once by the code that opens the scope and read by everything inside it, which is the shape request context actually has.
Common misconception: It is a ThreadLocal with nicer syntax.
Do child threads see the binding?+
Threads started inside the bound period inherit the bindings in effect. With StructuredTaskScope the bindings are captured when the scope is created, and every forked subtask reads them. Threads that already existed, such as pooled workers, inherit nothing.
Can you set a different value for a nested scope?+
Yes. A nested where rebinds the same key for the duration of a nested run or call, and the previous value is back when it returns. It is a documented feature, used for recursion counters, nested transactions and re-entrant framework calls.
What the API forbids is reading with nothing bound: get() throws NoSuchElementException. Rebinding is how an inner layer changes only what its own callees see.
Common misconception: Rebinding the same scoped value in a nested scope is forbidden and throws.
What should be true about the value you bind?+
It should be immutable, because child threads share the same object rather than receiving copies. If it cannot be immutable, every access has to be synchronized, which puts the concurrency problem back on the table.
Where does a scoped value not fit?+
Two-way flows where a callee publishes to a faraway caller, per-thread caches of expensive mutable objects, and unstructured work with no block that owns it. Those stay ThreadLocal, or become something else entirely.
Scoped values finished preview in JDK 25; StructuredTaskScope is still a preview API, so a project on JDK 25 can need --enable-preview for the scope while the scoped value itself is a permanent API.
Follow-up: Which of the two APIs is final in the JDK you build against?