ThreadLocal problem #1: memory

Each thread carries a copy. Millions of virtual threads = millions of copies. Memory explosion.

Advertisement

ThreadLocal problem #1: memory

Each thread carries a copy. Millions of virtual threads = millions of copies. Memory explosion.

Advertisement

ThreadLocal problem #2: cleanup

Forgot to remove()? Leak. Long-lived threads accumulate garbage.

ScopedValue: bounded lifetime

ScopedValue.where(auth, alice).run(() -> ... ). Value lives only inside the lambda. Auto-cleaned.

ScopedValue: immutable

Can't be modified within a scope. Nested scope shadows, doesn't mutate. Predictable.

Sharing across VTs

ScopedValue is inherited by structured concurrency child tasks. ThreadLocal isn't (by default).