Java / Java 21 Virtual Threads Interview questions
What is a ScopedValue and why was it introduced?
A ScopedValue (JEP 446, preview in Java 21) is an immutable value that's bound only for the duration of a specific call and automatically visible to any child threads it spawns, without needing manual propagation.
static final ScopedValue<String> USER_ID = ScopedValue.newInstance(); ScopedValue.where(USER_ID, "user-42").run(() -> { process(); // USER_ID.get() == "user-42" here and in any forked children });
It was introduced as a lighter, safer alternative to InheritableThreadLocal for virtual-thread-heavy code: values are write-once and scoped, avoiding the memory-leak risk of forgetting to call remove(), and avoiding the copy overhead when spawning many child virtual threads.
More Related questions...