Skip to content
javahacks.dev
Concurrency

Java ScopedValue vs ThreadLocal in Practice on Java 25

Compare ScopedValue and ThreadLocal in Java 25: immutability, bounded lifetime, inheritance by forked tasks, memory cost with virtual threads and migration.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the OpenJDK, Spring, Gradle and Apache Maven logos.

Both classes carry context, such as the current user or a trace id, to code several calls down without adding a parameter to each method. They differ in lifetime and mutability, and that difference decides which one is safe in a service that serves thousands of requests on a handful of pooled threads. ScopedValue became a final API in JDK 25 through JEP 506, so on a current JDK you can use it without --enable-preview.

What ThreadLocal does, and where it bites

java
private static final ThreadLocal<User> CURRENT = new ThreadLocal<>();

void handle(Request r) {
    CURRENT.set(authenticate(r));
    try {
        service.process();
    } finally {
        CURRENT.remove();
    }
}

The value is stored in a map owned by the current thread. It is mutable, since any code below can call CURRENT.set(...), and it stays until somebody calls remove() or the thread dies. On a platform thread pool the thread outlives the request by hours, so every request that forgets the finally block leaves its user behind for the next one. That is the failure we see most often in review: a set in a servlet filter, an early return before the try, and two weeks later a support ticket where one customer saw another customer's name in a header. The leak is also a memory problem, because the value keeps its whole object graph alive, and in an application server it can pin a class loader after redeploy. The diagnosis is covered in ThreadLocal leaks.

Inheritance is the second sore spot. A new thread does not see the parent's value unless you used InheritableThreadLocal, and that class copies the whole map at thread creation. With a pool the copy happens once, when the worker is created, so a pooled worker holds whatever the first caller had. Most people who reach for it discover this in production.

What ScopedValue does instead

java
private static final ScopedValue<User> CURRENT = ScopedValue.newInstance();

void handle(Request r) {
    ScopedValue.where(CURRENT, authenticate(r))
               .run(() -> service.process());
}

// anywhere below, on the same thread or in a forked subtask
User u = CURRENT.get();

The binding exists only while run executes. When the lambda returns or throws, the binding is gone, and there is no finally to forget. Inside the scope the value is read only: there is no set. If a nested call needs a different value, you rebind with another where(...).run(...), and the inner binding hides the outer one only until the inner call returns. That nesting is the part that feels odd to people used to ThreadLocal, and it is also the reason the class cannot leak: lifetime follows the call stack, the same way a local variable's does.

get() throws NoSuchElementException when nothing is bound. Use isBound() or orElse(defaultValue) at an edge where the value is optional, and let it throw in the deep layers where its absence means a programming error. For code that returns a result, use ScopedValue.where(...).call(...), which takes a callable that may throw.

Side by side

ThreadLocalScopedValue
LifetimeUntil remove() or thread deathThe run or call block
Mutable by calleeYesNo, rebind to change
CleanupManual, easy to missAutomatic
Memory with 1,000,000 virtual threadsOne map entry per thread that sets itOne binding, shared by reference
Reaches child threadsOnly through InheritableThreadLocal (copy)Inherited by threads forked in a structured scope
Reaches a plain ExecutorService taskNoNo

The last row matters. A scoped value is not inherited by a task you submit to an ordinary executor, because that thread was not forked inside the scope. If your code does that today with a ThreadLocal, it was already broken, and ScopedValue makes the break loud instead of silent.

Structured concurrency and the inheritance rule

StructuredTaskScope is the API that forks subtasks inside a scope, and the threads it creates inherit the bindings of the thread that opened it. A trace id bound at the edge of a request is therefore visible in every subtask without anyone copying it. Be aware that StructuredTaskScope is still a preview API in JDK 25 (JEP 505, fifth preview), so code that forks through it needs --enable-preview, while code that only binds and reads scoped values does not. The pairing is described in structured concurrency in practice.

Virtual threads change the arithmetic

A virtual thread supports thread locals, and each one gets its own map. With a few hundred platform threads that is cheap. When a service creates one virtual thread per request and a library stores a 4 KB buffer in a ThreadLocal to avoid allocation, 100,000 concurrent requests hold 400 MB of buffers that no longer serve their purpose, because the whole point of the per-thread cache was reuse across many tasks on the same thread. Virtual threads are not reused, so the cache never pays for itself. A scoped value avoids the multiplication because the reference is shared, not copied. More on the model is in virtual threads explained.

This is also why we would not carry a ThreadLocal cache into code that is moving to virtual threads. Either use a pool of the buffers or allocate, and measure which is cheaper on your hardware, because short-lived allocation is often faster than people expect.

Migrating request context

  1. List the thread locals that carry request-scoped data: the user, the tenant, a trace or correlation id, a locale.
  2. At the entry point (a servlet filter, a message listener, a scheduled job), replace the set and finally { remove } pair with ScopedValue.where(...).run(...) or call(...).
  3. Replace each CURRENT.get() reader as is. The method name is the same, so most call sites do not change.
  4. Search for code that sets the value from the middle of a call chain. That is the real work: a callee that mutates context for its caller needs to return the new value, or the caller needs to rebind.
  5. Keep ThreadLocal for per-thread caches, and for anything a library you do not control reads.

Frameworks that read thread locals internally keep doing so. Spring's SecurityContextHolder and MDC logging in SLF4J both use them, so your scoped value does not replace those; it supplements them. If your logging relies on MDC, copy the trace id into it at the same entry point where you bind the scoped value, and clear it in the same finally. Moving a service wholesale is covered in moving to virtual threads.

Rebinding inside a scope

A pattern worth knowing is the narrowed context. A request is bound to a user, and one call inside it must run as a system account to write an audit row.

java
ScopedValue.where(CURRENT, SYSTEM_USER).run(() -> audit.record(event));

Inside the lambda, CURRENT.get() returns the system user. Immediately after it, the original user is visible again. With a ThreadLocal you would write the old value to a local, set the new one, and restore it in a finally, and the day somebody skipped the restore you would have an escalation bug.

Where ThreadLocal is still the right tool

A per-thread cache of an expensive object that is not safe to share, such as a SimpleDateFormat or a parser instance, still fits ThreadLocal, provided the threads are long-lived platform threads. Library code that must run on JDK 21 or older has no choice. And ScopedValue is the wrong place to carry mutable state between layers: if the callee has to tell the caller something, return it.

For the specification, read JEP 506 and the ScopedValue Javadoc.

Also inJava Core
Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.