Sub topic 11
ScopedValue compared with ThreadLocal
This chapter assumes you know basic Java threads, lambdas, and the earlier chapters' where(...).run(...) binding. You compare ScopedValue with ThreadLocal on mutability, lifetime, and cost, then decide which to use.
The same task, two ways
Both classes give code deep in a call chain access to a value without passing it as a parameter. The difference is who controls the value's life.
public class Compare {
static final ThreadLocal<String> TL_USER = new ThreadLocal<>();
static final ScopedValue<String> SV_USER = ScopedValue.newInstance();
public static void main(String[] args) {
TL_USER.set("alice");
try {
System.out.println("ThreadLocal: " + TL_USER.get());
} finally {
TL_USER.remove();
}
ScopedValue.where(SV_USER, "alice")
.run(() -> System.out.println("ScopedValue: " + SV_USER.get()));
}
}With ThreadLocal, you must call remove() yourself. If you forget, the value stays on the thread. A pooled thread then carries a stale user into its next task. With ScopedValue, the binding ends when run returns, even if it throws.
Key differences
| Aspect | ThreadLocal | ScopedValue |
|---|---|---|
| Mutability | `set` can change the value at any time, from any code on the thread | Immutable inside a scope. There is no `set`. |
| Lifetime | Until `remove()` or thread death | Only while `run` or `call` executes |
| Rebinding | Overwrites, so you must restore the old value yourself | Nested `where` shadows, then the outer value returns |
| Child threads | `InheritableThreadLocal` copies values | Not inherited by `new Thread`. Structured concurrency can share them. |
| Cost with many threads | Each thread may hold its own copy | Bindings are shared, not copied |
Why mutability matters
A ThreadLocal is hidden mutable state. Any method can call set, so you cannot tell by reading a caller what a callee did to the value. A scoped value can only be read by callees. The value you bound is the value they see, so you can reason about the code locally.
Cost and virtual threads
A ThreadLocal stores its value in a map owned by each thread. That is cheap with a few platform threads. It becomes a memory cost when an application creates millions of virtual threads and each one holds its own copy. A scoped binding lives with the scope, not in a per-thread map. The next chapters cover virtual threads in more detail.
Choosing between them
Use ScopedValue when you need to share read-only context, such as a user, request ID, or transaction, for the duration of one call. Keep ThreadLocal when code needs per-thread mutable state that outlives a single call, such as a reusable non-thread-safe buffer, or when you are bound to a library API that uses it.
Exercise
A web handler stores the current user in a ThreadLocal, and a worker thread from a pool later reports the wrong user. What likely went wrong, and how does ScopedValue prevent it?
Show answer
The handler did not call remove(), so the value stayed on the pooled thread and leaked into the next task. A ScopedValue binding ends automatically when run returns, even after an exception, so no stale value can remain.