Sub topic 13
Sharing bindings with forked subtasks
This chapter assumes you can declare a ScopedValue, bind it with where(...).run(...), and read it with get. You should also know that a plain new Thread does not inherit bindings. You need a rough idea of what a thread pool and a Callable are. You don't need prior experience with structured concurrency.
The gap to close
Earlier you saw that a thread created with new Thread sees USER as unbound. That is a problem for real request handling, because a request often splits into parallel pieces such as a profile lookup and an order lookup. Each piece still needs the current user and request ID.
You could pass the values as parameters to every task, but that brings back the plumbing scoped values were meant to remove. Java solves this with StructuredTaskScope, which forks subtasks that automatically inherit the bindings of the thread that opened the scope.
Availability
StructuredTaskScope is in java.util.concurrent. It is a preview API in every release that includes it, so you need --enable-preview to compile and run code that uses it.
| Java release | ScopedValue | StructuredTaskScope |
|---|---|---|
| 21 to 24 | Preview | Preview, with `ShutdownOnFailure` and `ShutdownOnSuccess` subclasses |
| 25 | Final | Preview, reshaped around `StructuredTaskScope.open()` and joiners |
The examples below use the Java 25 API. A Java 21 to 24 version appears later in the chapter. In both cases the inheritance rules for bindings are the same.
Inheritance in action
The owner thread binds two scoped values, then opens a scope and forks two subtasks. Each subtask reads the bindings without receiving them as arguments.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class ForkedContext {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice")
.where(REQUEST_ID, 42)
.run(() -> {
try {
handle();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
static void handle() throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> profile =
scope.fork(() -> "profile of " + USER.get());
Subtask<String> orders =
scope.fork(() -> "orders of " + USER.get()
+ " (request " + REQUEST_ID.get() + ")");
scope.join();
System.out.println(profile.get());
System.out.println(orders.get());
}
}
}Run it with java --enable-preview --source 25 ForkedContext.java. The output is:
profile of alice
orders of alice (request 42)The subtasks run on other threads, yet USER.get() succeeds. Nothing in handle or the lambdas mentions the context.
What "inherit" means
The subtask thread gets the same bindings as the owner thread had when the scope was opened. It does not get a copy of the value. Both threads see the same immutable binding.
This is why scoped values are safe to share. A binding can't be changed by set, because no such method exists. A subtask can't alter what the owner or its siblings see.
Rebinding inside a subtask
A subtask may use its own nested where to rebind a value, exactly as in the nested-scopes chapter. The rebinding is visible only inside that subtask's call chain.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class SubtaskRebind {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> plain = scope.fork(() -> USER.get());
Subtask<String> elevated = scope.fork(() ->
ScopedValue.where(USER, "admin").call(() -> USER.get()));
scope.join();
System.out.println(plain.get()); // alice
System.out.println(elevated.get()); // admin
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(USER.get()); // alice
});
}
}The elevated subtask sees admin only while its inner call runs. plain and the owner still see alice.
The same code on Java 21 to 24
Before Java 25 you used one of two scope subclasses. The bindings behave identically. Only the scope API differs, and scoped values themselves also need --enable-preview on these releases.
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class ForkedContextOld {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Subtask<String> profile =
scope.fork(() -> "profile of " + USER.get());
scope.join().throwIfFailed();
System.out.println(profile.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
}Use ScopedValue.where(...).run(...) the same way on both releases.
Rules that keep the model sound
Inheritance depends on the scope's lifetime being nested inside the binding's lifetime. Three rules follow from that.
- Open the scope inside the binding. If you open the scope before calling
where(...).run(...), the subtasks inherit nothing. ReadingUSERthere throwsNoSuchElementException, andUSER.isBound()returnsfalse. - Don't change bindings between opening the scope and forking. If the owner enters a new
where(...).run(...)after the scope is open and then callsfork, the owner's bindings no longer match the ones the scope captured.forkthrowsStructureViolationException. Rebind inside the subtask instead, as shown above. - Close the scope where you opened it. Using try-with-resources keeps the scope's lifetime strictly inside the binding. Forgetting to
joinorclosecan also raiseStructureViolationException.
Here is the first mistake, with the failure visible:
import java.util.concurrent.StructuredTaskScope;
public class WrongOrder {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
ScopedValue.where(USER, "alice").run(() -> {
scope.fork(() -> USER.isBound()); // forked task sees false
});
scope.join();
}
}
}On Java 25 this program throws StructureViolationException, because fork runs under a binding that did not exist when the scope was opened. Either way, the fix is the same: move the try block inside run.
Threads that do not inherit
Only subtasks forked from a StructuredTaskScope inherit bindings. The following do not:
- A
Threadmade withnew ThreadorThread.ofVirtual().start(...). - Tasks submitted to an
ExecutorService, including a virtual-thread-per-task executor. CompletableFuture.supplyAsynctasks.
All of these start with an empty binding set. If a task running in one of them needs the user, pass the value as an argument, or restructure the code so that a scope does the forking.
The reason is lifetime. A binding exists only while its run call is on the stack. An executor task could still be running after run returns, and the binding would then outlive the scope that defined it. A StructuredTaskScope guarantees every subtask finishes before the scope closes, so inheritance stays safe.
Mutable values are still your responsibility
The binding is immutable, but the object bound can be anything. If you bind a HashMap and two subtasks write to it, you have a data race. Bind immutable objects such as strings, records with immutable fields, or List.copyOf(...) results. If you need shared mutable state, use a thread-safe type and treat the binding as a way to reach it.
Exercise
A request handler runs ScopedValue.where(USER, "alice").run(...). Inside the lambda it opens a StructuredTaskScope, then enters ScopedValue.where(USER, "bob").run(...) and calls scope.fork(() -> USER.get()) from inside that inner call. What happens, and how would you get a subtask that sees "bob"?
Show answer
The fork call throws StructureViolationException. The owner's bindings changed after the scope was opened, so they no longer match the bindings the scope captured. To get a subtask that sees "bob", open the scope inside the inner where("bob") call, or fork normally and have the subtask itself call ScopedValue.where(USER, "bob").call(() -> USER.get()).
Exercise
Why does a task submitted to Executors.newVirtualThreadPerTaskExecutor() see USER as unbound even though it runs on a virtual thread and the caller has a binding?
Show answer
Only subtasks forked from a StructuredTaskScope inherit bindings. An executor task can outlive the run call that created the binding, so Java does not copy bindings to it. Pass the value as an argument, or fork with a StructuredTaskScope instead.