跪拜 Guibai
← Back to the summary

ScopedValue Migration: Why Request Context Vanishes in Child Threads and How to Fix It (JDK 25)

Replace ThreadLocal with ScopedValue, why does request context 'disappear' in child threads? Three boundaries + complete migration guide (JDK 25)

Real scenario: after upgrading from JDK 21 to 25, we replaced the ThreadLocal that carries request context with ScopedValue. Unit tests all passed. But as soon as load testing hit concurrency, downstream audit logs showed userId=null and broken traceId chains. It took a long time to locate the issue, which all turned out to be on the thread pool and async callback paths. This article explains this frequently asked interview question and real migration pitfalls in one go: why it gets lost, where the boundaries are, and how to migrate safely. It is suitable for folks who are moving to virtual threads or preparing for JDK 25. Suggest saving it before reading carefully.

1. Incident site: three code snippets trigger NoSuchElementException

First, look at code that will almost certainly break after migration:

static final ScopedValue<RequestContext> CTX = ScopedValue.newInstance();

ScopedValue.where(CTX, new RequestContext("req-9527", 1001L)).run(() -> {
    System.out.println(CTX.get().traceId());          // ok req-9527

    Thread.startVirtualThread(() ->
        System.out.println(CTX.get().traceId()));     // error NoSuchElementException

    pool.submit(() -> CTX.get().traceId());           // error same
    CompletableFuture.supplyAsync(() -> CTX.get());   // error same

    try (var scope = StructuredTaskScope.open()) {
        scope.fork(() -> CTX.get().traceId());        // ok the only official inheritance channel
        scope.join();
    }
});

CTX.get();   // error binding already invalid after run/call

Notice two points that differ from old experience:

First, establish the mental model with an analogy:

ThreadLocal stores things for a thread; ScopedValue issues a pass for a call stack. The pass is valid only in this building; if you climb out the window (unstructured thread), you must get a new one yourself.

Don't blame JDK for being mean; see what problem it actually tries to solve.

2. Root cause: JDK takes away "inheritance"

Three old accounts from the ThreadLocal era

Recall the old pattern with InheritableThreadLocal + reused thread pool:

static final InheritableThreadLocal<RequestCtx> CTX = new InheritableThreadLocal<>();

void handle(Request req) {
    CTX.set(new RequestCtx(req.traceId(), req.tenant())); // mutable, lives as long as the thread
    try { dispatch(req); }
    finally { CTX.remove(); }   // miss an exception branch -> next request mixes tenants
}
// tasks submitted to the pool: sometimes inherit, sometimes read old values from reused threads, a superstitious scene

JDK wants to eliminate exactly three things:

  1. Unbounded lifecycle: the value is attached to the thread object; forgetting remove() leaks. Mechanically, in ThreadLocalMap the Entry key is a weak reference and the value is a strong reference, forming long-term retention on pooled threads.
  2. Arbitrary mutability: a utility class three layers down casually calls set(), and the value read at the sixth layer changes; nobody can trace who changed it.
  3. Expensive inheritance: InheritableThreadLocal copies a full writable copy per key when creating a child thread, O(N) cost, and memory cannot hold up under millions of virtual threads.

ScopedValue's choice: binding follows the call stack

ScopedValue attaches the value to the dynamic scope of where(...).run/call: pushes when entering, automatically restores the previous binding on return or exception. Implementation-wise it is an immutable snapshot singly linked list + bitmask + thread-level small cache, and run() internally has try-finally restore logic.

So why not let thread pools inherit? This is not "can't pass", it's "dare not pass":

JEP 506 says plainly: a parent thread's scoped values are inherited only by child threads created by StructuredTaskScope; traditional thread management classes like ForkJoinPool do not support inheritance because they cannot guarantee child threads finish before the parent thread exits the scope.

OpenJDK lead Alan Bateman also wrote on the mailing list: scoped values can only be safely inherited in a structured context, and the only API currently using this mechanism is StructuredTaskScope.

What happens if inherited? The parent scope is already unbound, but the child thread is still reading - that is a dangling binding. StructuredTaskScope uses join()/close() to weld the lifetime of child tasks into the code block, making inheritance safe.

image.png

Here is a counterintuitive point, and I think it is a good thing: ThreadLocal's pitfall is "dirty read residue"; ScopedValue's pitfall is "cleanly lost". The former occasionally mixes data and makes you doubt life; the latter stably throws an exception. Exploding in the test environment is better than leaking to production. Fail-fast itself is a protection.

The root cause can be said in one sentence, but the real pitfalls are hidden in three boundaries, especially the second; most people trip there.

3. Three boundaries: the key points of this question

Boundary 1: propagation boundary - only "structured parent-child" inherits

ScopedValue's inheritance doesn't spread automatically by "what the parent thread is currently bound to". Instead, StructuredTaskScope captures a binding snapshot at open(), and fork()ed subtasks share that snapshot. Without fork, there is no snapshot.

Subtask outlet Can it read the context? Reason
Same-thread method call / nested call yes still in the same call stack, dynamic scope
StructuredTaskScope.fork() yes open() captures snapshot, fork shares pointer, close() locks lifetime
new Thread() / Thread.startVirtualThread() no inheritance logic is written in fork, not in Thread constructor
ExecutorService.submit() / newVirtualThreadPerTaskExecutor no pool threads are not in your scope; even per-task new thread doesn't help, submit != fork
CompletableFuture.*Async / parallelStream no default uses ForkJoinPool.commonPool()
MQ callbacks / scheduled tasks / Netty event loop / Reactor callbacks no not in the request stack at all; scope may have already exited

Key point: virtual threads are only a thread form, not a context propagation protocol. Thread.startVirtualThread != StructuredTaskScope.fork; don't treat "is virtual thread" as "can inherit".

Boundary 2: time boundary - scope is the lifecycle fence

ThreadLocal's binding follows the thread; if the thread doesn't die, the value may stay (hence memory leaks). ScopedValue's binding follows the code block; as soon as run/call returns, it evaporates immediately, unrelated to whether the thread dies.

The trickiest pitfall is escaping tasks: after submit() you immediately return, the parent request is over, and only then does the queued task get scheduled - even if it is a "child thread", the stack no longer has the binding.

image.png

The second high-frequency pitfall: capture happens at open(), not fork(). open() takes a snapshot of the current thread's bindings; fork() also checks that the current binding is strictly consistent with open(), and throws StructureViolationException if inconsistent.

// error: at open() not bound yet, at fork() binding changed
try (var scope = StructuredTaskScope.open()) {
    ScopedValue.where(CTX, ctx).run(() -> {
        scope.fork(() -> queryUser());   // StructureViolationException
        scope.join();
    });
}

The correct order is always: bind first, then open, finally fork/join; or establish a narrower context inside the subtask itself. Binding is structural; you can't "insert it midway".

image.png

Boundary 3: value semantics - immutable, stack shadowing, hard failure

Habits carried from ThreadLocal basically all change here:

ThreadLocal habit ScopedValue reality
set() anytime to overwrite no set(), only nested where rebinding (shadowing)
inner change visible to outer shadowing only affects inner stack; exiting restores outer value
get() returns null if no value throws NoSuchElementException, hard failure
orElse(null) fallback JDK 25 no longer allows null
put mutable objects in immutable binding != thread-safe value object; mutable objects still need synchronization

To "change" a value, use nested where for shadowing; exiting the stack auto-restores, no manual rollback needed:

RequestCtx.run(ctx, () -> {
    RequestCtx.run(ctx.withTenant("sub-tenant"), () -> {
        RequestCtx.current().tenantId();   // sub-tenant: inner shadowing
    });
    RequestCtx.current().tenantId();       // outer original value, auto-restore on pop
});

Two practical tips:

Bonus: boundary 4 - ecosystem boundary, API finalization != ecosystem ready

Component JDK 25 status Production impact
ScopedValue Final (JEP 506) can go to production directly, no flag
StructuredTaskScope Preview #5 (JEP 505) need --enable-preview for compile and run, cross-version compatibility risk
MDC / SecurityContextHolder / TransactionSynchronizationManager / RequestContextHolder all ThreadLocal can't replace, only bridge

Here is a valuable insight: transaction and connection binding cannot propagate via ScopedValue. DB operations in child threads are new transactions; don't expect them to roll back with the main thread. So the realistic answer is a hybrid architecture: read-only context on ScopedValue, mutable state (transactions, connections, security) stays on ThreadLocal.

With the three boundaries clear, here is code you can copy directly.

4. Three-way comparison: a table to understand selection

Dimension ThreadLocal InheritableThreadLocal ScopedValue (JDK 25)
Ownership thread object thread object code block (dynamic scope)
Lifecycle as long as thread, need manual remove same as left within run/call block, auto destroy
Mutability arbitrary set child copy can change once bound read-only, nested shadowing
Propagation does not propagate copies whole table on thread creation, O(N) only fork inherits, shared immutable snapshot, O(1)
Unbound read returns null returns null throws NoSuchElementException
Thread pool risk dirty data + leak copy timing mess clean: if you can't get it, you can't
Million virtual threads per-thread map, memory bloat copies again per child thread shared reference, zero copy
Cleanup hand-written remove() hand-written none needed
Observability basically none same as left jcmd JSON thread dump can see task tree
Status final final JEP 506 final; companion STS still preview

Why is the gap orders of magnitude under million virtual threads? InheritableThreadLocal copies a writable copy per key for every child thread; ScopedValue's value is immutable, parent and child share the same reference, fork just copies a pointer. Official cost comparison is also blunt: in massive virtual thread scenarios, ThreadLocal's memory bloat and get() hash lookup overhead are clearly higher.

5. Migration code: six segments you can copy

First, a warning: lots of code online is still the old preview style - ScopedValue.runWhere/callWhere, new StructuredTaskScope.ShutdownOnFailure() + join().throwIfFailed(). JDK 25 has unified to where(...).run/call and StructuredTaskScope.open() + Joiner; ShutdownOnFailure and subclasses are removed. fork() return type and get() method names also changed across preview versions. Don't stubbornly memorize class names when reading old articles; remember "fork inside binding, join before return" is enough.

1. Aggregate context into immutable record, facade to close off

Don't have N ScopedValue bindings each separately. The official per-thread small cache defaults to only 16 entries (adjustable with -Djava.lang.ScopedValue.cacheSize). Scattered bindings of dozens of keys will blow up the cache and raise get() overhead. Pack into one record, bind once, cache-friendly:

public final class RequestCtx {

    /** read-only context packed once: trace, user, tenant, pass-through bag */
    public record Ctx(String traceId, long userId, String tenantId,
                      Map<String, String> baggage) {
        public Ctx {
            Objects.requireNonNull(traceId, "traceId");
            Objects.requireNonNull(tenantId, "tenantId");
            baggage = baggage == null ? Map.of() : Map.copyOf(baggage); // deep immutable
        }
        // want to "change" a field? return new object, never mutate in place
        public Ctx withTenant(String newTenantId) {
            return new Ctx(traceId, userId, newTenantId, baggage);
        }
    }

    // key privatized: key is "access ability", do not make it public
    private static final ScopedValue<Ctx> CTX = ScopedValue.newInstance();

    /** only one read entry point for the whole chain, error message should be human */
    public static Ctx current() {
        return CTX.orElseThrow(() -> new IllegalStateException(
                "Request context not bound: did it cross thread pool/async callback?"));
    }

    /** fallback for non-critical paths like logging */
    public static String traceIdOr(String def) {
        return CTX.isBound() ? CTX.get().traceId() : def;
    }

    public static void run(Ctx ctx, Runnable task) {
        ScopedValue.where(CTX, ctx).run(task);
    }

    public static <T> T call(Ctx ctx, Callable<T> task) throws Exception {
        return ScopedValue.where(CTX, ctx).call(task);
    }
}

Technical highlight: orElseThrow turns "context lost" from implicit NoSuchElementException into a business exception with a human message, doubling troubleshooting efficiency; key privatization + facade method gives downstream exactly one read path, eliminating "dual context".

2. Bind once at entry point, wrap the whole request chain

Binding must go to the outermost layer - Filter / Interceptor / AOP, don't bind midway in a service. In Spring Boot, put it in the Filter layer to avoid scope misalignment between interceptor and Filter:

public class ContextBindingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        var ctx = new RequestCtx.Ctx(
                traceIdOf(req), userIdOf(req), tenantOf(req), Map.of());
        // call can return a value, throw checked exceptions, no need to swallow and wrap in try/catch
        RequestCtx.call(ctx, () -> { chain.doFilter(req, res); return null; });
        // out of scope auto cleanup, no finally remove
    }
}

3. Parallel fan-out inside a request: structured concurrency

// note: JDK 25's StructuredTaskScope is still preview, need --enable-preview for compile and run
Response handle(Request req) throws Exception {
    var ctx = new RequestCtx.Ctx(req.traceId(), req.userId(), req.tenant(), Map.of());

    return RequestCtx.call(ctx, () -> {                        // 1 bind first
        try (var scope = StructuredTaskScope.open(             // 2 then open scope, order must not reverse
                Joiner.awaitAllSuccessfulOrThrow(),
                cfg -> cfg.withName("order-aggregate")
                          .withTimeout(Duration.ofMillis(800)))) {

            var user  = scope.fork(() -> userService.load(RequestCtx.current().userId()));
            var order = scope.fork(() -> orderService.recent(RequestCtx.current().userId()));
            var risk  = scope.fork(() -> riskService.check(RequestCtx.current().traceId()));
            // subtasks automatically inherit CTX: no need to pass parameters layer by layer, no object copy

            scope.join();   // 3 any failure -> others auto-cancel; get() must be after join
            return assemble(user.get(), order.get(), risk.get());
        }
    });
}

Technical highlight: fork starts a virtual thread by default, shares the same record reference with the parent, zero copy; withTimeout + Joiner makes "any failure cancels the rest" declarative; context and task tree lifetime align strictly, no dangling state where "request already returned, child thread still reading context". With withName and JDK 25's JSON thread dump (jcmd Thread.dump_to_file -format=json dump.json), you can directly see the task hierarchy; troubleshooting is no longer facing a pile of unrelated stacks.

4. Can't migrate existing thread pool? Snapshot at submit, rebind at execution

This is the most practical fallback tool during migration; it essentially turns implicit passing into explicit:

public final class ContextPropagatingExecutor implements Executor {

    private final Executor delegate;

    public ContextPropagatingExecutor(Executor delegate) {
        this.delegate = delegate;
    }

    @Override
    public void execute(Runnable task) {
        // 1 capture snapshot on the thread that submits the task, never wait for the worker thread to read
        var snapshot = RequestCtx.current();

        // 2 establish independent scope on the actual executing thread
        delegate.execute(() -> RequestCtx.run(snapshot, task));
        // 3 auto unbind after task execution, no remove()
    }
}

You can also treat Carrier directly as a "transportable binding snapshot" - it's just an immutable key-to-value map, constructing on thread A and executing on thread B is perfectly legal:

static <T> Callable<T> withContext(Callable<T> task) {
    // must materialize snapshot on the submitting thread
    ScopedValue.Carrier carrier = ScopedValue.where(CTX, CTX.get());
    return () -> carrier.call(task::call);   // each execution rebuilds a layer of binding
}

Technical highlight: the value is immutable, so the snapshot can be safely captured across threads; even if the task queues for a long time and the parent request is long over, the subtask uses its own rebuilt binding, not dependent on whether the parent thread is alive. where is rebuilding a layer of binding, not "passing the ThreadLocalMap over" - the semantics are explicit and auditable, much easier to troubleshoot than implicit inheritance.

Three accompanying reminders:

If even the decorator feels heavy, the most stable fallback is: take the value on the main thread and pass it directly as a parameter into the lambda. Ugly, but never wrong.

5. MDC bridge: log chain must not break

MDC is still ThreadLocal under the hood. Without bridging, the context is correct but traceId is empty in logs, and you'll misjudge "lost again" during troubleshooting:

static AutoCloseable mdcBridge(RequestCtx.Ctx ctx) {
    MDC.put("traceId", ctx.traceId());
    return MDC::clear;   // pooled threads are reused, not clearing gives dirty logs
}

try (var _ = mdcBridge(ctx)) {   // JDK 22+ unnamed variable, nice
    business.handle();
}

Especially in virtual thread scenarios, don't forget clear. Same for SecurityContext, OTel Context: inject within the where scope, clear when leaving scope; don't pass three sets of context separately.

6. Dual-write during migration + gray switch

@Component
public class RequestContextFilter extends OncePerRequestFilter {

    @Value("${ctx.scoped-value.enabled:false}")
    private boolean useScoped;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp,
                                    FilterChain chain) throws ServletException, IOException {
        var ctx = new RequestCtx.Ctx(req.getHeader("X-Trace-Id"),
                Long.parseLong(req.getHeader("X-User-Id")),
                req.getHeader("X-Tenant-Id"), Map.of());
        LegacyThreadLocal.set(ctx);              // old path fallback
        try {
            if (useScoped) {
                RequestCtx.call(ctx, () -> { chain.doFilter(req, resp); return null; });
            } else {
                chain.doFilter(req, resp);
            }
        } finally {
            LegacyThreadLocal.remove();          // old path must remove
        }
    }
}

During gray rollout, do "ThreadLocal old value vs ScopedValue new value" dual-read reconciliation metrics; watch traceId consistency rate; only remove old code after the difference rate hits zero.

This section is a bit long; suggest saving it. If you are migrating to JDK 25, you might follow; this series will keep updating. Code is here, but how to deploy without crashing needs rhythm.

6. Migration roadmap: five steps, don't go all at once

image.png

Phase Action Acceptance
0. Inventory classify ThreadLocal usages into four: 1 request-level read-only context, 2 per-thread heavy object cache (SimpleDateFormat class), 3 mutable accumulator/transaction state, 4 framework bidirectional passing (Security, OTel, MyBatis) only 1 migrates; 2/3/4 explicitly don't migrate or have other plans
1. Entry binding + immutable model top-level where().call() in Filter/Interceptor/Netty Handler; context as record, inner collections immutable isBound()==false outside scope; exception paths auto unbind
2. Bridge dual-write keep old ThreadLocal fallback + switch gray + MDC bridge dual-read consistency metrics, difference rate 0
3. Parallel path refactor Executors/CompletableFuture -> StructuredTaskScope; those that can't change use "capture-rebind" decorator; MQ/RPC write traceId/tenantId/deadline to headers, consumer deserializes then re-where; scheduled tasks explicitly construct SYSTEM_CONTEXT, don't fake request context under concurrency load, context loss rate 0; no StructureViolationException
4. Cleanup and solidify delete remove()/finally, privatize keys, add scope unit tests two tests below must be written

When to use which? Decision diagram for your reference:

image.png

Two unit tests that must be written, nailing down "scope semantics", better than any document:

@Test
void bindingMustDisappearAfterException() {
    assertThrows(IllegalStateException.class, () ->
        ScopedValue.where(KEY, "req").run(() -> {
            assertEquals("req", KEY.get());
            throw new IllegalStateException("boom");
        }));
    assertFalse(KEY.isBound());   // exception path must also unbind
}

@Test
void nestedBindingMustRestoreOuterValue() {
    ScopedValue.where(KEY, "outer").run(() -> {
        ScopedValue.where(KEY, "inner").run(() -> assertEquals("inner", KEY.get()));
        assertEquals("outer", KEY.get());   // inner exit auto restore
    });
}

If this article only gets one table across, remember this one.

7. Difficulty and solution quick reference table

# Difficulty Root cause / symptom Solution
1 Pooled/async thread can't read context binding propagates along scope tree, pool threads not in tree prefer StructuredTaskScope.fork(); existing pool uses "snapshot at submit + rebind at execution" decorator
2 StructureViolationException after open(), changed binding then fork strictly "where before open"; wrap template method, forbid business code writing raw
3 Task escape, scope already ended but still running lifetime mismatch join() to close; add withTimeout; forbid fire-and-forget; result-dependent tasks must wait
4 Want to "modify" context no set(), rebinding only downward new value with nested where shadowing; accumulators use subtask return values and parent aggregates, don't put into ScopedValue
5 Context mistakenly treated as immutable record shell immutable, inner collections still writable deep immutable: Map.copyOf/List.copyOf + code review rule
6 MDC / Security / OTel not aware they still read ThreadLocal bridge dual-write at boundary; Reactor path uses Micrometer context-propagation contextCapture()/ContextSnapshot
7 get() blows up chain / orElse(null) banned unbound hard failure critical path orElseThrow fast fail; truly optional data use isBound() + orElse(non-null default)
8 New and old coexist during migration some code reads TL, some SV, values inconsistent entry dual-write + gray switch + consistency reconciliation, gradually converge read paths
9 Preview API production risk JDK 25 structured concurrency still preview 5 only treat finalized ScopedValue as stable dependency; isolate STS in adapter layer, don't let Subtask type leak into business interfaces
10 Load test find get() slower bindings too scattered, blow up per-thread cache; hot loop rebinding aggregate into one record one bind; never rebind in hot path
11 Security semantics misuse orElse(0L)/default user masks absence identity, tenant context always orElseThrow; orElse only for clearly legal defaults
12 thenApplyAsync wrapping for nothing no executor falls back to commonPool every hop in async chain explicitly pass wrapped executor

8. High-frequency follow-ups: what interviewers want to dig

Q1: What exactly makes ScopedValue faster than ThreadLocal? Three things: no hash lookup of ThreadLocalMap; value immutable, thousands of threads share the same snapshot; bind/unbind is stack operation, JIT-friendly. The gap is most noticeable under million virtual threads.

Q2: Virtual thread unmount then remount, will context be lost? No. Binding is not attached to the carrier thread, it's attached to the virtual thread's scope snapshot - that's exactly why it was designed for Project Loom.

Q3: Why doesn't ForkJoinPool get inheritance? It can't guarantee the subtask finishes before the parent scope ends; inheriting would be dangling. close() locks the lifetime; only then inheritance holds.

Q4: So can ThreadLocal be completely deleted? Don't do it all at once. Thread-level heavy object caches, mutable accumulators, transaction/connection - ThreadLocal is still a reasonable choice; caches like SimpleDateFormat, the modern solution is to switch to immutable DateTimeFormatter. Read-only request context -> ScopedValue, thread-level mutable state -> ThreadLocal, choose by scenario.

Q5: Someone asks about "create-and-inherit" abilities like Thread.ofVirtual().inheritScopedValues()? In essence it's copying the current snapshot at creation, can't save the scenario where "tasks queue until after the scope ends", and it's even less recommended as a substitute for structured concurrency.

Q6: What does this have to do with business like AB experiments? A lot. Experiment context (experimentId + bucketing result) is a standard request-level read-only context: passing via ScopedValue completely eliminates "mixed buckets" from thread pool dirty reads; but async reporting threads for exposure/click are not in the task tree, must explicitly snapshot and pass, otherwise the metrics lose context and experiment data gets polluted. This kind of problem in the ThreadLocal era is "occasional dirty read"; in the ScopedValue era it becomes "stable error", which is easier to catch before launch.

9. In closing

Context "disappearing" is not a migration failure; it's JDK forcing you to change from "implicit inheritance" to "explicit scope". Write the three boundaries again:

Production reality is a three-layer hybrid architecture: ScopedValue carries the read-only context backbone, Carrier snapshot decorator transitions unbounded boundaries, ThreadLocal continues to manage transactions and mutable state. Migration motto for you: bind once at entry, fork auto passes, rebind on pool exit, value must be immutable.

Implementation advice is just three: inventory first, only migrate read-only context; gray dual-write plus reconciliation, don't go all at once; shut preview features into adapter layer, leave a retreat for the future.

Finally, a question for interaction: When migrating virtual threads or ScopedValue, what's the most outrageous context problem you've stepped on? Is NoSuchElementException exploding in your face, or silently mixing tenants? Chat in comments, I'll pick a few typical ones for the next issue. If useful, like, in-read, share three times to support; next in series covers failure propagation and timeout control in structured concurrency. Follow to not miss it.