Video in progress

How do ScopedValue and structured concurrency change context passing built on ThreadLocal? How do you plan the migration in a big codebase?

ScopedValue (final in JDK 25, JEP 506) binds a value immutably, only for the duration of an explicit block: cleanup can't be forgotten, it is cheap with virtual threads, and it is inherited safely by child tasks. Structured concurrency (still a preview in JDK 25) provides this inheritance. I start the migration by listing all the ThreadLocals and the framework boundaries.

📖 Answer

The ThreadLocal problems are known: a leak and context bleed if remove() is forgotten, a copy in every new thread for InheritableThreadLocal (expensive with millions of virtual threads), and a value that can be changed from anywhere.

With ScopedValue:

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

void handle(Request req) {
    ScopedValue.where(CTX, RequestContext.from(req)).run(() -> service.process());
    // once you leave the block the value is gone, no cleanup needed
}

void deepInside() {
    RequestContext ctx = CTX.get();   // NoSuchElementException if not bound
}

With structured concurrency, subtasks opened inside a StructuredTaskScope automatically see the parent's ScopedValues, with no copying.

The differences and limits:

  • the value is immutable: the "I'll fill it in later" pattern doesn't work, and if needed you rebind in an inner block;
  • a task submitted to an ordinary ExecutorService doesn't inherit a ScopedValue, only structured concurrency does;
  • structured concurrency is still a preview and the API may change, so on prod it requires --enable-preview.

The migration plan:

  1. Inventory. Find and categorize all ThreadLocal/InheritableThreadLocals: request context (user, tenant, trace), caches (formatter, buffer), and framework internal state.
  2. Caches: not to ScopedValue but to a thread-safe shared object (DateTimeFormatter) or a pool.
  3. Request context: at the entry point (a filter, a consumer) use ScopedValue.where(...).run(...). For the lower layers a small facade: Context.current(), which checks ScopedValue first and the old ThreadLocal after. This facade joins the two worlds during the transition.
  4. Frameworks. Spring Security, MDC and OpenTelemetry still rely on ThreadLocal for now: watch for their new versions and bridge them in your own facade.
  5. A static analysis rule: a new ThreadLocal only with review.

I'm in no hurry with this: ScopedValue is final, but the ecosystem has to be ready. The first step is to use it in new code with virtual threads, and a facade for the old code.