Java 25 (LTS) · Topic 1 of 4
Scoped values
Definition​
A scoped value (Java 25) shares data with the code you call, for example the current user, without passing it as a parameter. The value is fixed for the duration of one run and is safe to share with virtual threads, which makes it a cleaner replacement for ThreadLocal.
Example code​
The current user, available to every method inside run()
class Demo {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static void handleRequest() {
System.out.println("Handling a request for " + USER.get()); // no parameter needed
}
public static void main(String[] args) {
ScopedValue.where(USER, "asha").run(Demo::handleRequest);
ScopedValue.where(USER, "ravi").run(Demo::handleRequest);
System.out.println("bound outside run? " + USER.isBound());
}
}
// Output:
// Handling a request for asha
// Handling a request for ravi
// bound outside run? false
Finished this page? Track your progress (saved only in your browser).