跪拜 Guibai
← All articles
Backend · Interview · Java

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

By Rain的Java大神之路 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Context loss now fails loudly instead of silently corrupting data, but only if you restructure async code to structured concurrency. Mixed architecture is the realistic end state: ScopedValue for read-only request context, ThreadLocal for transactions and mutable state.

Summary

The shift from ThreadLocal to ScopedValue in JDK 25 is not a drop-in replacement. ScopedValue binds context to a code block's dynamic scope, so it does not automatically propagate to threads created outside a structured scope. Unbound reads throw NoSuchElementException instead of returning null, and orElse(null) now NPEs, making context loss loud but exposing every async gap.

Only StructuredTaskScope.fork() inherits the parent's binding. ExecutorService, CompletableFuture.*Async, and new Thread calls do not. The timeline also matters: open() captures a snapshot, fork() verifies it is unchanged, and rebinding after open throws StructureViolationException. Tasks submitted to a pool and executed after the parent scope exits will read nothing.

The migration path uses a hybrid architecture: ScopedValue for read-only request context, Carrier snapshot decorators to bridge existing executors, and ThreadLocal for mutable state like transactions and MDC. The article provides six ready-to-copy code segments, a five-phase roadmap, and a quick-reference table of twelve common pitfalls.

Takeaways
— Unbound ScopedValue.get() throws NoSuchElementException, not null; JDK 25 bans orElse(null).
— Only StructuredTaskScope.fork() inherits parent bindings; thread pools, CompletableFuture async methods, and raw Thread.startVirtualThread do not.
— open() captures the binding snapshot; rebinding after open and before fork throws StructureViolationException. Correct order is bind, open, fork, join.
— ScopedValue has no set(); to change a value, use nested where() shadowing, which restores automatically on stack exit.
— Wrapped executors must capture the snapshot on the submitting thread and rebind on the executing thread; in async chains, each hop must explicitly pass the wrapped executor.
— JDK 25 marks ScopedValue final (JEP 506), but StructuredTaskScope is still preview #5 (JEP 505) and requires --enable-preview.
— Only migrate request-level read-only context; mutable state like transactions, connections, and MDC stays on ThreadLocal.
— MDC and SecurityContext still read ThreadLocal, so they require explicit bridge code that clears on exit to avoid dirty logs.
— Test exception paths and nested bindings with unit tests: assert that binding disappears after an exception and that inner shadowing restores the outer value.
— Use orElseThrow for identity and tenant fields; never use orElse(0L) or anonymous defaults that mask missing context.
— Aggregate all context fields into a single immutable record to fit the per-thread cache (default 16 entries) and avoid get() overhead.
— During migration, keep dual-write with a gray switch, measure traceId consistency, and only remove LegacyThreadLocal after difference rate reaches zero.
Conclusions

Fail-fast is a safety win: ScopedValue turns silent tenant-mixing bugs into exceptions caught in tests, whereas ThreadLocal's dirty reads often escape to production.

The real cost of migration is not the API change but restructuring code to structured concurrency; existing thread pool code needs explicit snapshot/rebind decorators, which many teams will skip.

The ecosystem boundary is the hidden trap: libraries like MDC and Spring Security are still ThreadLocal-bound, so a pure ScopedValue rollout is impossible without bridge layers.

ScopedValue's design implicitly pushes teams toward structured concurrency as a required discipline, not an optional pattern, because unstructured threads simply lose context.

The article's claim that 'capture at submit, rebind at execute' is always safe depends on immutable value objects; teams using mutable inner collections will still corrupt state even when the binding survives.

Concepts & terms
ScopedValue
A final (JEP 506) Java mechanism that binds a value to a dynamic code block via where(...).run/call. It is read-only, pushed on entry, and automatically restored on exit. Unbound reads throw NoSuchElementException.
StructuredTaskScope
A preview API (JEP 505) for structured concurrency. open() captures a snapshot of the current scope, fork() starts a virtual thread that shares that snapshot, and join()/close() guarantees subtasks finish before the parent scope exits. It is the only automatic inheritance channel for ScopedValue.
Dynamic scope
A scope defined by the execution stack rather than lexical nesting. ScopedValue bindings live in the dynamic scope of a run/call block, so method calls and forked subtasks inside that block see the binding, while threads created outside it do not.
Carrier
ScopedValue.Carrier is an immutable key-to-value mapping produced by ScopedValue.where(). It can be constructed on one thread and applied on another (via carrier.call), effectively acting as a transportable binding snapshot for explicit propagation.
StructureViolationException
Thrown when a fork() is called with a different binding than captured at open(). Enforces the rule that bindings are captured before the scope opens and cannot be changed mid-scope.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗