Virtual threads and structured concurrency question 119 of 180 senior
What is a ScopedValue, and why is it preferred to ThreadLocal here?
- A
ThreadLocalwith a shorter name - Correct: An immutable value bound for the duration of a call, inherited by structured forks, with no set/remove lifecycle and therefore no leak
- A value scoped to a class
- A replacement for method parameters in general
ThreadLocal is mutable, unbounded in lifetime and must be removed by hand, which is unmanageable when
threads number in the millions and are created per task. InheritableThreadLocal copies the whole map
per child, which is worse.
ScopedValue inverts it: the value is bound for the dynamic extent of a call and automatically
unbound at the end, it cannot be reassigned by callees, and structured forks share the parent's binding
by reference rather than copying.
private static final ScopedValue<Principal> USER = ScopedValue.newInstance();
ScopedValue.where(USER, principal).run(() -> handleRequest()); // USER.get() inside
Use it for context that is genuinely ambient (request id, principal, tenant) and pass everything else as a parameter.
Quiz yourself on Virtual threads and structured concurrency Suggest a correction