ScopedValue became a permanent Java API in Java 25, after several preview iterations. It is part of the java.lang package.
Creating a ScopedValue Object
We can easily create a new ScopedValue object by calling the ScopedValue.newInstance() method. Once the object was created we can easily attach it with key-value pairs.
private static final ScopedValue car = ScopedValue.newInstance();
ScaopedValue Code Sample
The following code sample shows how easy it is to create a ScopedValue object and share a key-value pair across multiple function calls using the ScopedValue object we created.
public class ScopedValueDemo {
private static final ScopedValue USER = ScopedValue.newInstance();
static void main() {
ScopedValue.where(USER, "David").run(ScopedValueDemo::processRequest);
}
static void processRequest() {
System.out.println("Processing request for " + USER.get());
writeLog();
}
static void writeLog() {
System.out.println("Writing log for " + USER.get());
}
}
The output we get when running this code is:
Processing request for David
Writing log for David
ScopedValue provides Java developers with a structured mechanism for sharing contextual information across method calls without polluting APIs with parameters that intermediate methods do not need.







