Scoped Values With Structured Concurrency: Inheritance, Use Cases and Migrating From ThreadLocal
StructuredTaskScope subtasks inherit scoped-value bindings without copying, and forking under a different binding throws StructureViolationException. Use cases (depth guards, joining a unit of work, shrinking deadlines), a ThreadLocal migration checklist, and when to keep ThreadLocal.
kvi5hnuCode Sprout team member9 min readOn this page
Article 40 showed that plain threads and executor tasks don't inherit scoped values. Structured subtasks do. A StructuredTaskScope guarantees that every subtask finishes before the scope closes, and the scope closes before the run or call that made the bindings returns. So a subtask can safely share the owner's bindings: they're guaranteed to outlive it. This article shows the inheritance rules, three patterns that scoped values express well, and how to migrate thread-local code.
Inheritance through scopes
When a scope is opened, it captures the owner's current scoped-value bindings. Every subtask forked into the scope runs with those bindings, and so do subtasks of scopes they open. Nothing is copied: all subtasks refer to the same bindings.

The program runs a quote inside a request binding, with a nested scope and a subtask that rebinds, and then breaks the rules on purpose. It uses the Java 27 preview StructuredTaskScope API (java --enable-preview ContextTree.java on Java 27, no flag on Java 28). ScopedValue itself is final.
import java.util.List;
import java.util.concurrent.StructureViolationException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
public class ContextTree {
record RequestContext(String traceId, String tenant) {}
static final ScopedValue<RequestContext> CONTEXT = ScopedValue.newInstance();
static final ScopedValue<String> ROLE = ScopedValue.newInstance();
static String whoAmI(String task) {
return task + " sees " + CONTEXT.get().traceId() + "/" + CONTEXT.get().tenant()
+ " as " + ROLE.orElse("user") + " on " + (Thread.currentThread().isVirtual() ? "a virtual thread" : "a platform thread");
}
static List<String> legs() throws Exception {
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow())) {
scope.fork(() -> whoAmI(" leg LIS-AMS"));
scope.fork(() -> whoAmI(" leg AMS-OSL"));
return scope.join();
}
}
static void quote() throws Exception {
try (var scope = StructuredTaskScope.open(Joiner.<Object>allSuccessfulOrThrow())) {
scope.fork(() -> whoAmI("1. hotel"));
scope.fork(ContextTree::legs); // a nested scope inherits too
scope.fork(() -> ScopedValue.where(ROLE, "pricing-bot") // a subtask may rebind for its own calls
.call(() -> whoAmI("2. pricing")));
for (Object result : scope.join()) {
if (result instanceof List<?> lines) lines.forEach(System.out::println);
else System.out.println(result);
}
}
}
static void forkUnderDifferentBinding() throws Exception {
try (var scope = StructuredTaskScope.open(Joiner.<String>allUntil(s -> false))) {
ScopedValue.where(ROLE, "admin").run(() -> {
try {
scope.fork(() -> whoAmI("never runs"));
} catch (StructureViolationException e) {
System.out.println("3. fork inside a new binding: StructureViolationException");
}
});
scope.join(); // nothing was started; allUntil's join() doesn't throw
}
}
public static void main(String[] args) throws Exception {
var ctx = new RequestContext("t-101", "acme");
ScopedValue.where(CONTEXT, ctx).call(() -> { quote(); return null; });
ScopedValue.where(CONTEXT, ctx).call(() -> { forkUnderDifferentBinding(); return null; });
}
}
Output:
1. hotel sees t-101/acme as user on a virtual thread
leg LIS-AMS sees t-101/acme as user on a virtual thread
leg AMS-OSL sees t-101/acme as user on a virtual thread
2. pricing sees t-101/acme as pricing-bot on a virtual thread
3. fork inside a new binding: StructureViolationException
- Subtasks see the owner's bindings. The hotel subtask read
CONTEXTon its own virtual thread. So did the two legs, two levels down, in a scope opened by a subtask. No subtask received the context as a parameter. - Subtasks can rebind for their own calls. The pricing subtask bound
ROLEtopricing-botfor the code it called. That binding is local to the subtask's thread: its siblings and the owner never see it. - The owner can't fork under a different binding. The owner opened the scope with no
ROLEbinding, then tried to fork insidewhere(ROLE, "admin"). The bindings atforkno longer matched those captured atopen(), soforkthrewStructureViolationException. Without this rule, a subtask could outlive theadminbinding it was started under.
The rule is easy to follow: bind first, then open the scope. If some subtasks need a different value, rebind inside the subtask, or open a separate scope inside the new binding.
Why inheritance is cheap
An InheritableThreadLocal copies its entries into each child thread's map when the child is created. A scoped binding is shared: forking 10,000 subtasks that read the request context copies nothing. Each subtask only refers to the same binding, and since the value is immutable, there's nothing to synchronize.
Patterns that fit scoped values
Each of these needs context that is fixed for a section of code, can be overridden by nested code, and must end with it: exactly what rebinding gives. The program runs all three on plain Java 25.
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class Solution {
// 1. A depth guard: each nested level rebinds the counter
static final ScopedValue<Integer> DEPTH = ScopedValue.newInstance();
static final int MAX_DEPTH = 4;
static final Map<String, List<String>> BUNDLES = Map.of(
"grand-tour", List.of("iberia", "nordics"),
"iberia", List.of("lisbon", "porto"),
"nordics", List.of("oslo", "arctic"),
"arctic", List.of("tromso", "nordics")); // a mistake: arctic includes nordics again
static List<String> expand(String item) {
int depth = DEPTH.orElse(0);
if (depth > MAX_DEPTH) throw new IllegalStateException("bundles nested deeper than " + MAX_DEPTH + " at " + item);
List<String> parts = BUNDLES.get(item);
if (parts == null) return List.of(item);
List<String> out = new ArrayList<>();
for (String part : parts) out.addAll(ScopedValue.where(DEPTH, depth + 1).call(() -> expand(part)));
return out;
}
// 2. Join the caller's unit of work if there is one, otherwise start one
static final class AuditBatch {
final String name;
final List<String> events = new ArrayList<>(); // only touched by the thread that owns the binding
AuditBatch(String name) { this.name = name; }
}
static final ScopedValue<AuditBatch> BATCH = ScopedValue.newInstance();
static <T> T inBatch(String name, Supplier<T> action) {
if (BATCH.isBound()) {
System.out.println(" " + name + " joins batch " + BATCH.get().name);
return action.get();
}
AuditBatch batch = new AuditBatch(name);
T result = ScopedValue.where(BATCH, batch).call(action::get);
System.out.println(" flush " + batch.name + ": " + batch.events);
return result;
}
static void record(String event) {
BATCH.get().events.add(event);
}
static int bookHotel() {
return inBatch("hotel", () -> { record("hotel booked"); return 2; });
}
static int bookTrip() {
return inBatch("trip", () -> { record("flight booked"); int nights = bookHotel(); record("trip confirmed"); return nights; });
}
// 3. Deadlines that nested code can shorten but never extend
static final ScopedValue<Instant> DEADLINE = ScopedValue.newInstance();
static final Instant START = Instant.parse("2026-11-20T10:00:00Z"); // a fixed clock keeps the output stable
static <T> T withinBudget(Duration budget, Supplier<T> action) {
Instant wanted = START.plus(budget);
Instant effective = DEADLINE.isBound() && DEADLINE.get().isBefore(wanted) ? DEADLINE.get() : wanted;
return ScopedValue.where(DEADLINE, effective).call(action::get);
}
static String budgetLeft() {
return Duration.between(START, DEADLINE.get()).toMillis() + " ms";
}
public static void main(String[] args) {
System.out.println("1. iberia expands to " + expand("iberia"));
try {
expand("grand-tour");
} catch (IllegalStateException e) {
System.out.println(" grand-tour: " + e.getMessage());
}
System.out.println("2. booking a trip:");
bookTrip();
System.out.println(" booking a hotel on its own:");
bookHotel();
System.out.println("3. request budget: " + withinBudget(Duration.ofSeconds(2), () ->
budgetLeft()
+ "; a call asking for 5 s gets " + withinBudget(Duration.ofSeconds(5), Solution::budgetLeft)
+ "; one asking for 500 ms gets " + withinBudget(Duration.ofMillis(500), Solution::budgetLeft)
+ "; afterwards " + budgetLeft()));
}
}
Output:
1. iberia expands to [lisbon, porto]
grand-tour: bundles nested deeper than 4 at tromso
2. booking a trip:
hotel joins batch trip
flush trip: [flight booked, hotel booked, trip confirmed]
booking a hotel on its own:
flush hotel: [hotel booked]
3. request budget: 2000 ms; a call asking for 5 s gets 2000 ms; one asking for 500 ms gets 500 ms; afterwards 2000 ms
1. Depth guards
expand rebinds DEPTH one higher for each nested level, and each level reads its own depth. No counter has to be passed through the recursion or decremented on the way back: when a nested call returns, its binding is gone and the caller's depth is visible again. The data contained a cycle (arctic includes nordics), and the guard stopped it instead of overflowing the stack. The same pattern detects re-entrancy: isBound() tells a framework method whether it's already running further up the stack.
2. Joining an existing unit of work
inBatch checks whether a batch is already bound. If it is, the call joins it. If not, it creates one, binds it, and flushes it at the end. Booking a trip produced one batch with three events, including the hotel's. Booking a hotel on its own produced its own batch. That's the shape of flattened transactions ("join the current transaction if there is one") and of request-wide caches or audit trails. The bound object is mutable here, and that's acceptable only because the binding is used by one thread. If the work forked subtasks that record events, the batch would need a thread-safe list.
3. Deadlines that only shrink
withinBudget binds the earlier of the caller's deadline and its own. A nested call asking for 5 seconds inside a 2-second request still got 2 seconds, and one asking for 500 ms got 500 ms. When the nested calls returned, the request's own deadline was back. This is how deadline propagation works in RPC frameworks. With structured concurrency, the remaining time can feed withTimeout for nested scopes.
Migrating from ThreadLocal
| Thread-local code | Scoped-value code |
|---|---|
TL.set(v); try { work(); } finally { TL.remove(); } | ScopedValue.where(SV, v).run(() -> work()) |
T r; TL.set(v); try { r = compute(); } finally { ... } | T r = ScopedValue.where(SV, v).call(() -> compute()) |
TL.get() returning null when unset | SV.orElse(default), SV.isBound(), or SV.get() if a binding is required |
changing the value mid-request with set | rebinding for a nested call: where(SV, newValue).run(...) |
| save, set, restore for nested contexts | nothing: rebinding restores automatically |
InheritableThreadLocal to reach child threads | StructuredTaskScope subtasks inherit bindings |
| capturing and reinstalling for executor tasks | the same, explicitly: var v = SV.get(); pool.submit(() -> where(SV, v).call(...)) |
Steps that work in practice:
- Find where the value is set. The places that call
set()become thewhere(...).run(...)calls. Ifset()is called in many places deep in the code, the context isn't really fixed per section, and the code needs restructuring first. - Make the value immutable, typically a record.
- Keep the accessor. If callers use
Context.current(), only its implementation changes, and call sites stay as they are. - Replace inheritance with structured scopes, and make every unstructured hand-off explicit.
- Bridge legacy APIs while libraries catch up. If a logging library reads its context from a thread-local such as SLF4J's
MDC, set theMDCentries inside therunand clear them infinally, alongside the scoped binding.
When to keep ThreadLocal
Scoped values don't replace every thread-local:
- Per-thread caches of expensive, non-thread-safe objects on platform threads. A scoped value can't be set lazily from deep inside the code. Better still, use a thread-safe object or a pool (article 15).
- Values that callees must change for their callers to see, such as a counter that accumulates upward. A scoped binding flows only downward.
- Libraries that must run on releases before Java 25, where
ScopedValuewas a preview (21 to 24) or absent.
What's current
ScopedValueis final in Java 25 (JEP 506).StructuredTaskScopeis a preview in Java 25 to 27 and final in Java 28 (JEP 543). Inheritance into subtasks has worked the same way in every version of both.StructureViolationException(injava.util.concurrent) is thrown both for scopes closed out of order and for forks whose bindings differ from those captured atopen().- Frameworks are starting to offer scoped-value based context alongside their thread-local APIs, but most still use thread-locals today.
Common questions
Do subtasks see a binding the owner makes after opening the scope?
They can't: forking inside the new binding throws StructureViolationException, and forking after it ends uses the original bindings. Bind before opening the scope.
Can a subtask's binding leak to its siblings?
No. A binding made inside a subtask exists only on that subtask's thread, for the duration of its own run or call.
What happens to bindings if a subtask is cancelled?
Nothing special. The subtask's thread is interrupted and finishes, and its own nested bindings end as its calls unwind. The owner's bindings stay in effect until its run or call returns, which can't happen before the scope closes.
Is it safe to bind a mutable object and fork subtasks that modify it? Only if the object is thread-safe. Inheritance shares the reference, so subtasks modifying a plain collection would race. Prefer immutable values, and return results from subtasks instead.
Summary
- A
StructuredTaskScopecaptures the owner's scoped-value bindings atopen(). All subtasks, at any nesting depth, share them without copying. - Forking under different bindings than those captured throws
StructureViolationException. Bind first, then open the scope. - Subtasks can rebind for their own calls, and their bindings stay on their own threads.
- Rebinding expresses depth guards, re-entrancy checks, joining an existing unit of work, and shrinking deadlines without any cleanup code.
- Migrate by turning
set/removepairs intowhere(...).run(...), making values immutable, and replacingInheritableThreadLocalwith structured scopes. Keep thread-locals for per-thread caches and upward-flowing values.
Practice questions
An owner writes try (var scope = StructuredTaskScope.open()) { ScopedValue.where(USER, alice).run(() -> scope.fork(this::work)); scope.join(); }. What happens, and how do you fix it?
Answer
fork throws StructureViolationException, because the bindings at fork time (with USER bound) differ from those captured when the scope was opened (without it). Bind first and open the scope inside: ScopedValue.where(USER, alice).call(() -> { try (var scope = StructuredTaskScope.open()) { scope.fork(this::work); scope.join(); } return null; }).
A request binds a RequestContext and forks 5,000 subtasks that each read it. How much copying does inheritance do, and why is it safe without synchronization?
Answer
None: all subtasks refer to the same binding captured when the scope was opened. It's safe because the binding can't be changed, and the record it refers to is immutable. The scope's happens-before guarantees (article 34) make the owner's writes visible to the subtasks.
A framework stores a per-request List<String> of warnings in a thread-local, and deep code calls WARNINGS.get().add(...). Is this a good candidate for a scoped value?
Answer
Partly. The list can be bound once per request, and deep code can still add to it, because the binding itself doesn't change. But it's a mutable object: if the request forks subtasks that add warnings, the list must be thread-safe (for example ConcurrentLinkedQueue). A cleaner design has subtasks return their warnings and the owner combine them.
Review quiz
Test yourself on Part 5 with the Part 5 review quiz: Scoped Values in Java. It covers context passing, thread-local problems, the ScopedValue API, rebinding, and inheritance into structured subtasks.
Previous: ScopedValue in Java: Binding Context With where(), run() and call()
Next: Blocking vs Non-Blocking I/O in Java: Streams, NIO Channels and Buffers

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.