Java Concurrency Interview

Virtual threads and structured concurrency question 119 of 180 senior

What is a ScopedValue, and why is it preferred to ThreadLocal here?

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.

scoped-values virtual-threads

Quiz yourself on Virtual threads and structured concurrency Suggest a correction