Sub topic 12
What other threads see
This chapter assumes you know how ScopedValue.where(...).run(...) binds a value and how get, isBound, and orElse read it. It covers what happens when the code inside a scope starts other threads.
A binding belongs to a thread's scope
A scoped value binding is attached to the thread that called run. It lasts for the duration of that call. Code running on that thread, at any call depth inside the scope, sees the value. Code on any other thread does not, unless the platform copies the binding for you.
Plain new Thread(...) does not copy it. The new thread starts with an empty set of bindings, even if you create it inside a run block:
public class NotInherited {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
Thread t = new Thread(() -> System.out.println(USER.isBound())); // false
t.start();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}This program prints false. Calling USER.get() inside that thread would throw NoSuchElementException, as it does for any unbound scoped value.
The reason is the lifetime rule. A binding exists only while run is on the stack. A thread started with new Thread can outlive the run call, and then it would hold a value whose scope had already ended. Not inheriting by default removes that problem.
This differs from InheritableThreadLocal. That class copies values into every child thread at construction time, and the child keeps its copy for its whole life. Scoped values have no such default copy.
Which threads do see the binding
A thread sees a binding in two cases:
- It is the thread that called
run(orcall), and the scope is still active. - It was forked through a structured concurrency scope that was opened inside the binding.
The second case is the only automatic inheritance. The following diagram shows both cases and the case that fails.
Sharing bindings with forked subtasks
Structured concurrency treats a group of related threads as one unit of work. The scope that forks them waits for them, so they cannot outlive the code that created them. That guarantee is why the runtime can safely give subtasks the parent's bindings. The subtasks always finish before the run call that holds the binding can return.
The next example uses the Java 25 form of StructuredTaskScope. In Java 25 ScopedValue is a final feature, but StructuredTaskScope is still a preview API:
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Forked {
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> a = scope.fork(() -> "task A sees " + USER.get());
Subtask<String> b = scope.fork(() -> "task B sees " + USER.get());
scope.join();
System.out.println(a.get());
System.out.println(b.get());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}Compile and run it with preview features enabled:
javac --release 25 --enable-preview Forked.java
java --enable-preview ForkedBoth subtasks print alice. Neither received USER as a parameter.
Inherited bindings are shared, not copied, and they are immutable. A subtask cannot change the parent's value. It can only shadow it with a nested where(...).run(...) on its own thread, and that shadowing ends when the nested call returns, as in the nested-scope behavior from the earlier chapter.
Where inheritance does not happen
These common ways of starting work do not carry bindings:
| How the work starts | Sees the binding? |
|---|---|
| Direct method call on the same thread | Yes |
| `StructuredTaskScope.fork` inside the scope | Yes |
| `new Thread(...).start()` | No |
| `Thread.ofVirtual().start(...)` | No |
| `ExecutorService.submit(...)` | No |
| `CompletableFuture.supplyAsync(...)` | No |
The last two rows catch many people. A pooled thread was created long before your run call, so it cannot know about your binding. Even if the pool created a new thread for your task, the pool is not a structured scope and gives no guarantee that the task ends before the binding does.
Passing the value across manually
When you must use a thread or executor that does not inherit, read the value in the parent and rebind it in the child:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Handoff {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<String> result = ScopedValue.where(USER, "alice").call(() -> {
String user = USER.get(); // read on the parent thread
return pool.submit(() ->
ScopedValue.where(USER, user).call(() -> "worker sees " + USER.get()));
}).get();
System.out.println(result.get());
}
}
}The task reads USER on the parent thread, captures it in a local variable, and binds it again inside the worker. The worker's binding lasts only for that one call. The outer call returns the Future as soon as the task is submitted, so the parent's binding may already be gone while the worker runs. This is safe because the worker uses its own binding, not the parent's.
You can also skip the rebinding and pass user as an ordinary argument. That is often clearer when only one method needs it.
Design guidance for threads
- Prefer structured concurrency when you fork work that needs the context. You get inheritance and a guarantee that the work ends inside the scope.
- If you use an executor, decide at the task boundary whether the task needs the context. If it does, capture and rebind it there, not in scattered places inside the task.
- Check
isBound()at the entry points of code that may run on foreign threads. A clear failure at the entry is easier to debug than aNoSuchElementExceptionseveral calls deep. - Never treat the absence of a binding as a signal for default behavior in security-sensitive code. An unbound
USERon a pooled thread usually means a bug, not an anonymous user.
Exercise
A request handler runs inside ScopedValue.where(REQUEST_ID, 7).run(...). It calls executor.submit(() -> log(REQUEST_ID.get())) on a shared fixed thread pool. What happens when the task runs, and how would you fix it in two different ways?
Show answer
The pool thread has no binding for REQUESTID, so REQUESTID.get() throws NoSuchElementException inside the task (the exception appears when you call Future.get(), wrapped in an ExecutionException). Fix 1: read REQUESTID.get() in the handler, store it in a local variable, and pass it into the task, either as a method argument or by rebinding it with ScopedValue.where(REQUESTID, id).run(...) inside the task. Fix 2: replace the executor with a StructuredTaskScope opened inside the binding and use scope.fork(...), so the subtask inherits the binding.
Exercise
Why does the Java platform not copy scoped value bindings into every thread created with new Thread, the way InheritableThreadLocal copies values?
Show answer
A binding is valid only while the run or call that created it is on the stack. A thread made with new Thread can keep running after that call returns, so it would hold a value whose scope has ended. Structured concurrency subtasks are guaranteed to finish before their scope closes, so inheriting bindings into them is safe. For other threads, the platform leaves the binding out and you pass the value explicitly.