Q70: What are Scoped Values (Java 21 / Preview) and how do they improve upon ThreadLocal?
ScopedValue provides immutable, thread-confined value sharing suitable for thousands/millions of Virtual Threads.
- Improvements over
ThreadLocal:- Immutable: Cannot be modified once bound.
- Bounded Lifetime: Automatically unbound when scope exits (eliminates thread pool memory leaks).
- Efficient Inheritance: Child virtual threads share scope context efficiently.
Key Takeaways
- Immutable, bounded-lifetime alternative to
ThreadLocal. - Prevents memory leaks across thread executions automatically.
Knowledge Check
What is the key lifecycle safety advantage of ScopedValue over ThreadLocal?