Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is the difference between ScopedValue and ThreadLocal?
| ThreadLocal | ScopedValue (preview, Java 21+) |
| Mutable: set() can be called any number of times. | Bound once for the duration it's active, via where(...).run(...) or call(...). |
| Value persists until explicitly removed or the thread dies. | Value is only visible for the dynamic extent of the bound block, then automatically unbound. |
| Prone to leaks in pooled threads if remove() is forgotten. | Bounded lifetime by construction; nothing to forget to clean up. |
| Inherited by child threads only via the special InheritableThreadLocal, awkwardly, copied once at creation. | Designed to be cheaply and safely shared with structured subtasks, including many virtual threads. |
ScopedValue was introduced specifically to fit the virtual-thread and structured-concurrency model: since an application might spawn millions of short-lived virtual threads, a mutable per-thread map with manual cleanup, as ThreadLocal requires, becomes both a memory-leak risk and unnecessary overhead. ScopedValue instead binds a value only for a well-defined block of code and its callees, then automatically and safely unbinds it when that block exits.
More Related questions...