Sub topic 1
Why Context Is Hard to Share Across Method Calls
Prerequisites
This chapter assumes Core Java syntax, lambdas, functional interfaces, static fields, final, and a basic understanding of threads and the call stack. Familiarity with ThreadLocal is helpful.
Passing Context Through Calls
A request often has context such as a user name, request ID, or authorization data. Passing that context explicitly is clear, but it can make many method signatures noisy:
handle(request, user, requestId);
validate(request, user, requestId);
save(request, user, requestId);A method may need the context only because a method deeper in the call chain needs it. ThreadLocal avoids these extra parameters, but it stores mutable, thread-owned state. Values can remain installed after a task finishes, especially when thread pools reuse threads. Code can also change the value unexpectedly.
Scoped values provide read-only, dynamically scoped context. A value is available to the code called inside a bounded operation.
Availability and Status
Scoped values were preview features in Java 20 through Java 23. Java 25 provides the final API. Prefer Java 25 for production code. To experiment with a preview release, compile and run with the same release and --enable-preview, for example:
javac --enable-preview --release 23 Example.java
java --enable-preview ExampleDeclaring and Binding a Scoped Value
A ScopedValue<T> is a key whose current binding has type T. Declare it once, usually as a static final field. Bind it with where, then run an operation with run:
public class RequestContext {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(RequestContext::handle);
}
static void handle() {
System.out.println("Handling request for " + USER.get());
}
}USER is bound only while handle runs. Methods called by handle can read it without receiving it as a parameter. After run returns, the binding ends automatically.
Exercise
Why does ScopedValue reduce method-parameter noise?
Show answer
It lets called methods read a temporarily bound value without adding that value to every method signature.