Share data across call stacks safely without ThreadLocal pitfalls.
Porównanie kodu
✕ Java 8
static final ThreadLocal<User> CURRENT =
new ThreadLocal<>();
void handle(Request req) {
CURRENT.set(authenticate(req));
try { process(); }
finally { CURRENT.remove(); }
}
✓ Java 25
static final ScopedValue<User> CURRENT =
ScopedValue.newInstance();
void handle(Request req) {
ScopedValue.where(CURRENT,
authenticate(req)
).run(this::process);
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Immutable
Callees can read but never modify the scoped value.
Auto cleanup
No manual remove() — value is scoped to the block.
Virtual-thread safe
Works efficiently with millions of virtual threads.
Stare podejście
ThreadLocal
Nowoczesne podejście
ScopedValue
Od JDK
25
Poziom trudności
Zaawansowany
Wsparcie JDK
Scoped values
Dostępne
Finalized in JDK 25 LTS (JEP 506, Sept 2025).
Jak to działa
ScopedValue provides immutable, inheritable, scope-limited context. Unlike ThreadLocal, scoped values are automatically cleaned up, work with virtual threads, and can't be mutated by callees.
Powiązana dokumentacja