Sub topic 11
ScopedValue compared with ThreadLocal
This chapter assumes you can read Java lambdas, know that each thread has its own call stack, and have seen ThreadLocal at least once. It compares the two tools on mutability, lifetime, and cost. It ends with rules for choosing between them.
Two answers to the same problem
Both ThreadLocal and ScopedValue let code deep in a call chain read a value such as the current user without receiving it as a parameter. They differ in how the value is stored and in how long it lives.
- A
ThreadLocalties a value to a thread. The value lives until someone removes it or the thread ends. - A
ScopedValueties a value to a bounded piece of execution, theruncall. The value disappears whenrunreturns.
Most of the other differences follow from this one.
Availability
ScopedValue was a preview API in Java 21 through 24. It became a final API in Java 25. On a preview release you must compile and run with preview features enabled:
// javac --release 21 --enable-preview RequestContext.java
// java --enable-preview RequestContextThreadLocal has been available since Java 1.2 and needs no flags. The examples below use ScopedValue.where(...).run(...). On Java 25 or later they run without flags. On Java 21 to 24 they need --enable-preview.
Mutability
A ThreadLocal is a mutable slot. Any code running on the thread can call set or remove:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LeakyContext {
static final ThreadLocal<String> USER = new ThreadLocal<>();
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.submit(() -> USER.set("alice")).get();
pool.submit(() -> System.out.println("Next task sees: " + USER.get())).get();
pool.shutdown();
}
}The program prints Next task sees: alice. The first task set the value and never removed it. The pool reused the same thread, so the second task inherited a value it never asked for. In a web server, this kind of leak can show one user's data to another user's request.
A ScopedValue has no set method. Within one scope its value cannot change. To use a different value you open a nested scope, as covered in the chapter on rebinding.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ScopedContext {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.submit(() -> ScopedValue.where(USER, "alice")
.run(() -> System.out.println("Inside: " + USER.get()))).get();
pool.submit(() -> System.out.println("Next task bound? " + USER.isBound())).get();
pool.shutdown();
}
}The output is Inside: alice followed by Next task bound? false. The binding ended when run returned, so nothing is left on the pooled thread.
Lifetime
With ThreadLocal, correct cleanup depends on discipline. Every set needs a matching remove, normally in a finally block:
USER.set("alice");
try {
handle();
} finally {
USER.remove();
}If one code path forgets the finally, the value leaks. With ScopedValue the structure of the code enforces the lifetime. The binding exists exactly while the run lambda executes, including when it exits by exception.
Direction of data flow
A ThreadLocal allows two-way communication. A callee can set a new value and the caller will see it after the call returns. That is convenient, but it is hidden coupling. A reader cannot tell from a method signature that the method changes shared state.
A ScopedValue flows one way, from caller to callees. If a callee must send data back, it uses a return value or an exception. This makes the code easier to follow.
Cost
ThreadLocal values are stored in a map owned by each Thread object. This has three costs:
- Every thread that uses the variable gets its own map entry.
- Thread-pool threads keep their values after the task ends unless you remove them.
InheritableThreadLocalcopies the parent's values into each child thread when the thread is created. With millions of virtual threads, those copies add up.
A ScopedValue binding is shared by reference with everything inside the scope, and nothing is copied. Binding and unbinding are cheap, and there is no per-thread map to clean up. The design targets programs that create very many short-lived virtual threads.
Side-by-side summary
| Property | `ThreadLocal` | `ScopedValue` |
|---|---|---|
| Changing the value | `set` and `remove` at any time | Not possible. Open a nested scope instead. |
| Lifetime | Until `remove` or thread death | The `run` call only |
| Cleanup | Manual, usually `finally` | Automatic |
| Data flow | Two-way | Caller to callee only |
| Child threads | Not inherited. `InheritableThreadLocal` copies. | Not inherited by `new Thread`. Shared with structured-concurrency forks. |
| Default for no value | `initialValue()` or `null` | Unbound. `get` throws, or use `orElse`. |
| Status | Final since Java 1.2 | Preview in Java 21 to 24, final in Java 25 |
The diagram shows the difference in lifetime on a reused pool thread.
Behavior across threads
Neither type passes values to a plain new Thread. In the scoped-value case, the thread you start does not see the binding:
public class NotInherited {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
Thread t = new Thread(() -> System.out.println(USER.isBound())); // false
t.start();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}InheritableThreadLocal does copy values to new threads, but only when the thread is created, and each child gets its own copy. Changes made later in the parent are not seen by the child. For scoped values, the supported way to share a binding is StructuredTaskScope. Subtasks forked inside the scope see the parent's bindings, because they cannot outlive the scope that holds them. StructuredTaskScope was still a preview API in Java 25.
Choosing between them
Use ScopedValue when all of these hold:
- The data is set once at an entry point, such as a request handler, and then only read.
- Readers are called from inside that entry point's call chain.
- You run many threads, especially virtual threads, or you use thread pools where leaks are a risk.
Use ThreadLocal when:
- You need to change the value over time. A per-thread counter or a reusable non-thread-safe buffer, such as a
SimpleDateFormat, fits this case. - You must support Java versions before 21, or you cannot enable preview features on 21 to 24.
- A framework you depend on already exposes its context through
ThreadLocal, and you can't change it.
If a value needs to be mutable, you can bind a mutable object, such as an AtomicInteger, in a scoped value. The reference stays fixed, but the contents change.
Migrating a `ThreadLocal`
A typical migration has four steps:
- Replace
ThreadLocal<T>withScopedValue<T>, declaredstatic final, created withScopedValue.newInstance(). - Replace the
set/try/finally/removepattern at the entry point withScopedValue.where(KEY, value).run(...). - Replace
get()calls withget(), or withorElseororElseThrowwhere code may run outside any scope. - Look for callees that call
set. Change them to return a result, or restructure the code so the new value is bound in a nested scope.
Step 4 is where most of the effort goes. A ThreadLocal that is written in several places usually reflects a design that depends on hidden mutation, and it cannot be converted mechanically.
Common mistakes
- Reading outside a scope.
get()on an unboundScopedValuethrowsNoSuchElementException. AThreadLocalreturnsnullinstead. Code that depended on thatnullneedsorElseor anisBound()check. - Expecting a new thread to see the binding. Use structured concurrency for child tasks. Don't pass the value as a parameter only because you forgot this.
- Expecting to update a value. There is no
set. Use a nestedwhere(...).run(...). - Binding mutable state and then treating it as safe.
Exercise
A web server uses a thread pool and stores the current user in a ThreadLocal. Occasionally, a request sees the previous request's user. Explain the cause. Then say which property of ScopedValue removes the problem.
Show answer
A pooled thread is reused across requests. If a request calls set and never calls remove, for example because an exception skipped the cleanup, the value stays on the thread and the next request on that thread reads it. A ScopedValue binding exists only while the run call executes, so it is removed automatically when the scope exits, even when the scope exits by an exception. Nothing is left on the thread for the next request.
Exercise
Given static final ScopedValue<String> USER = ScopedValue.newInstance();, what does this code print, and why?
ScopedValue.where(USER, "alice").run(() -> {
new Thread(() -> System.out.println(USER.orElse("none"))).start();
});
Show answer
It prints none. A thread created with new Thread does not inherit scoped-value bindings, so USER is unbound inside it and orElse returns the default. To share the binding with a subtask, fork the subtask through StructuredTaskScope inside the scope.
Exercise
Name one situation in which ThreadLocal is still the better choice than ScopedValue.
Show answer
When the value must change during execution, for example a per-thread counter or a reusable buffer that the code modifies. ScopedValue is immutable within a scope. ThreadLocal is also the only option when you must run on Java versions before 21, or on 21 to 24 without enabling preview features.