Java / Java 21 Virtual Threads Interview questions
Why doesn't ThreadLocal work well with virtual threads?
ThreadLocal was designed under the assumption that threads are relatively few and long-lived, often reused via a pool, so caching a value per thread was cheap and effective.
With virtual threads, you may have millions of short-lived instances, each potentially allocating its own ThreadLocal entry. That multiplies memory usage and defeats the original caching intent, since there's no pooled thread to actually reuse the cached value on.
InheritableThreadLocal is worse still, because it must copy values down to every child thread, adding overhead at exactly the scale virtual threads are meant to avoid. Java 21's answer to this is ScopedValue.
More Related questions...