java / expert
Snippet
Scoped Values for Lightweight Data Sharing
Scoped Values (JEP 446) provide a modern, thread-safe alternative to ThreadLocal. They are designed for virtual threads and allow for the efficient, immutable sharing of data across method boundaries without the memory overhead and complexity of traditional thread-locals.
snippet.java
1
2
3
4
5
6
7
public final static ScopedValue<User> CURRENT_USER = ScopedValue.newInstance();void processRequest(User user) {ScopedValue.where(CURRENT_USER, user).run(() -> {service.performTask(); // Inherits the value});}
Breakdown
1
public final static ScopedValue<User> CURRENT_USER = ScopedValue.newInstance();
Defines a global ScopedValue container that will hold the contextual data.
2
ScopedValue.where(CURRENT_USER, user).run(() -> { ... });
Binds a value to the scope and executes the logic; the value is automatically cleared afterward.