Video in progress
What is ScopedValue, and in what ways is it better than ThreadLocal?
ScopedValue passes a value down a chain of calls for the duration of a block, and it disappears on its own when the block ends. It's immutable, it's inherited cheaply by child threads, and it's much lighter than ThreadLocal when there are many virtual threads. It was a preview in Java 21 and became final in JDK 25.
📖 Answer
ThreadLocal has three pain points:
- it's mutable: any code can call
set()and corrupt the caller's context; - its lifetime is unbounded: if you forget
remove(), the value lives as long as the thread (in a pool, forever); InheritableThreadLocalcopies the whole map to a child thread, and with a million virtual threads that's expensive.
ScopedValue is different:
static final ScopedValue<RequestContext> CTX = ScopedValue.newInstance();
void handle(Request req) {
ScopedValue.where(CTX, new RequestContext(req.userId(), req.traceId()))
.run(() -> service.process(req));
// here CTX is no longer bound
}
// deeper in the call chain
String user = CTX.get().userId();
The guarantees:
- the value is visible only inside the
runblock and disappears automatically when you leave it, so you can't forget cleanup; - there's no
set(); in an inner block you can only rebind, and the outer value doesn't change; - child threads started through
StructuredTaskScopeinherit the value without copying it.
When ThreadLocal should stay: a cache that really belongs to the thread (for example, a reusable buffer), or cases where the context doesn't fit a block structure. Another practical limit is that many frameworks (SLF4J MDC, Spring Security, transaction synchronization) are still built on ThreadLocal, so migration depends on their support.
On Java 21 you need --enable-preview to use it, and the API changed a little before JDK 25. For new code on JDK 25+, I recommend passing context through ScopedValue.
Sign up to mark studied questions and save your progress.