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:
    1. Immutable: Cannot be modified once bound.
    2. Bounded Lifetime: Automatically unbound when scope exits (eliminates thread pool memory leaks).
    3. 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?