Language: Java · Versions: Java 23 (--enable-preview, ScopedValue & StructuredTaskScope)
The problem
I'm binding a request context via ScopedValue.where(REQ_ID, "req-42").call(...) and inside that scope I create a StructuredTaskScope.ShutdownOnFailure. Inside one of the forked subtasks, a library registers an asynchronous cleanup or CompletableFuture.supplyAsync(...) callback on the common ForkJoinPool. While scope.fork(...) inherits the ScopedValue snapshot automatically, the CompletableFuture.supplyAsync(...) stage throws NoSuchElementException: ScopedValue not bound!
Minimal example
import java.util.concurrent.*;
public class ScopedValueTrap {
static final ScopedValue<String> REQ_ID = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
ScopedValue.where(REQ_ID, "req-42").call(() -> {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var task = scope.fork(() -> {
// Inherits REQ_ID ("req-42"):
String direct = REQ_ID.get();
// Spawns on ForkJoinPool.commonPool() outside StructuredTaskScope:
return CompletableFuture.supplyAsync(() -> direct + ":" + REQ_ID.get()).join();
});
scope.join().throwIfFailed();
System.out.println(task.get());
}
return null;
});
}
}
Expected
Understand why ScopedValue deliberately refuses to propagate to unstructured thread pools (CompletableFuture.supplyAsync) and how to bridge legacy Executor / CompletableFuture pipelines inside a ScopedValue + StructuredTaskScope hierarchy without risking use-after-scope-exit.
What happens instead
REQ_ID.get() inside CompletableFuture.supplyAsync throws java.util.NoSuchElementException because ScopedValue bindings are strictly tied to the structured lifetime of StructuredTaskScope.fork() threads (whose termination is awaited by scope.join()), whereas an unstructured ForkJoinPool task could outlive the ScopedValue.where(...) block.
What is the cleanest way in Java 23 to integrate APIs that return CompletableFuture or accept an Executor into a StructuredTaskScope so they preserve ScopedValue bindings safely?
Your premise holds. REQ_ID.get() on a thread with no binding throws NoSuchElementException. I'm reasoning from the JEP 481 design (third preview in 23) and haven't run your code. I can't confirm the exact message text you quote, so check that against your actual stack trace.
Why it fails
A ScopedValue binding lives in the dynamic scope of one thread, and StructuredTaskScope.fork copies it to the child. It does this because the scope's join() and close() guarantee the child ends before the where(...).call(...) block exits. A ForkJoinPool.commonPool() worker has no such guarantee, so it never gets the binding. There is no public API in 23 to capture a snapshot of all current bindings. That is deliberate: it keeps the lifetime guarantee.
Fix: rebind explicitly, with a wrapping Executor
Capture the value at submission and rebind it as a lexically scoped binding on the worker thread.
static Executor bindReqId(Executor delegate) {
return task -> {
// Capture on the submitting thread (it has the binding).
// If it can be unbound, check REQ_ID.isBound() first.
String id = REQ_ID.get();
delegate.execute(() -> ScopedValue.where(REQ_ID, id).run(task));
};
}
// inside the forked subtask:
var ex = bindReqId(ForkJoinPool.commonPool());
return CompletableFuture.supplyAsync(() -> REQ_ID.get(), ex).join();
If you only need the value, passing it as a parameter is simpler and has no hidden state. Your own direct + ":" + ... already does that: capture direct and don't call get() in the async stage.
What this does and doesn't guarantee
- Rebinding is safe for the data, because the value is immutable and the binding exists only for the duration of
run. - It does not restore structure. The async stage can still outlive the scope, which is the use-after-scope-exit risk you asked about. It will then carry a stale request ID, or touch a request-scoped resource that has been closed.
- To keep the lifetime bounded, join or cancel the future before the subtask returns. Your
.join()already does this. Any stage you don't join leaks out.
For an Executor-based API you control
Prefer doing the work inside the scope: call scope.fork(...) instead of supplyAsync. Forks may come from the owner or from threads already inside the scope's tree. You get inheritance, cancellation and the lifetime guarantee together.
For a third-party library that takes an Executor, pass the wrapper above. For a library that hard-codes the common pool, you can't fix it from outside. Pass the value as data, or wrap its callbacks yourself.
Two API details to check against the 23 javadoc, since this was reworked between previews. Carrier.call takes a Callable, while the static callWhere / getWhere use the new CallableOp. isBound() is the safe test before get().