Sub topic 4
Declaring a ScopedValue
This chapter covers how to declare a ScopedValue. It assumes you know Java lambdas, static fields, final, and the call stack. Familiarity with ThreadLocal helps but isn't required. The previous chapters explained why implicit context is awkward. Here the focus is the declaration itself, because it is short and easy to get subtly wrong.
A declaration creates a key, not a value
A ScopedValue<T> object doesn't hold data. It is a key that code uses to look up a value bound for the current scope. Declaring it only creates the key. Binding a value to the key is a separate step, covered in the next chapter.
The declaration looks like this:
import java.lang.ScopedValue;
public class RequestContext {
static final ScopedValue<String> USER = ScopedValue.newInstance();
}Four details matter here:
ScopedValuelives injava.lang, so the import is optional. It is shown only to make the origin clear.newInstance()is a static factory.ScopedValuehas no public constructor.- The type parameter
Tfixes what can be bound.USERaccepts onlyStringvalues, and the compiler enforces this. - No initial value is passed. A new scoped value is unbound everywhere until some code binds it.
Why the field is static final
Every call to newInstance() returns a distinct key. Two keys with the same type parameter are unrelated. A lookup succeeds only with the same key object that was used to bind the value.
public class DistinctKeys {
static final ScopedValue<String> A = ScopedValue.newInstance();
static final ScopedValue<String> B = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(A, "alice").run(() -> {
System.out.println(A.isBound()); // true
System.out.println(B.isBound()); // false
});
}
}This is why the idiom is static final. A static field gives every class one shared key to bind and read. A final field guarantees nobody reassigns the key. An instance field would create a new key per object, so code holding a different object would never see the binding. A key created inside a method would be unreachable from the callees that need it.
Choosing the type parameter
The type argument can be any reference type. Prefer a small immutable type, because the binding is only shallowly immutable. The key cannot be rebound in place, but if T is a mutable object, callers can still change its fields. A record is a good fit when you need several related fields.
public class SessionDemo {
record Session(String user, String role) {}
static final ScopedValue<Session> SESSION = ScopedValue.newInstance();
public static void main(String[] args) {
Session s = new Session("alice", "admin");
ScopedValue.where(SESSION, s).run(SessionDemo::audit);
}
static void audit() {
Session current = SESSION.get();
System.out.println(current.user() + " acts as " + current.role());
}
}Running this prints alice acts as admin. Notice that audit() takes no parameters. It finds the session through the shared key.
Primitive types need their wrapper types, as with any generic class. ScopedValue<Integer> is valid, and ScopedValue<int> does not compile.
Controlling who can bind and read
Because the key is an ordinary field, ordinary access modifiers control access. This is a useful design tool:
| Declaration | Who can bind | Who can read |
|---|---|---|
| `private static final` | Code in the same class | Code in the same class |
| `static final` (package-private) | Code in the same package | Code in the same package |
| `public static final` | Any code | Any code |
| `private` key plus a public static accessor method | Only the declaring class | Anyone, through the accessor |
The last row is a common pattern. It lets a framework bind the value while exposing only a read method:
public final class CurrentUser {
private static final ScopedValue<String> USER = ScopedValue.newInstance();
private CurrentUser() {}
public static void runAs(String name, Runnable task) {
ScopedValue.where(USER, name).run(task);
}
public static String name() {
return USER.get();
}
}Callers can call CurrentUser.runAs("alice", ...) and CurrentUser.name(), but they never touch the key. The code that controls the key controls how the value is set. A public key lets any caller rebind the value for its own callees, which may not be what you want for something like a security principal.
Declaring is not binding
A freshly declared scoped value is unbound. Reading it before any binding is a runtime error:
public class Unbound {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println(USER.isBound()); // false
System.out.println(USER.orElse("anonymous")); // anonymous
try {
USER.get();
} catch (java.util.NoSuchElementException e) {
System.out.println("get() failed: unbound");
}
}
}isBound() and orElse(...) are safe on an unbound key. get() throws NoSuchElementException. A later chapter covers these reading methods in detail. The point for now is that the declaration gives you no default. If you need one, supply it at the read site with orElse, or bind a value at the top of your program.
Declaration compared with ThreadLocal
The ThreadLocal declaration can carry a default through ThreadLocal.withInitial(...), and it exposes set and remove. A ScopedValue has neither. There is no setter on the key and no default at declaration. Values arrive only through a where(...).run(...) scope. This is what lets the runtime treat the binding as immutable and bounded.
| Aspect | `ThreadLocal<T>` | `ScopedValue<T>` |
|---|---|---|
| Create | `new ThreadLocal<>()` or `withInitial` | `ScopedValue.newInstance()` |
| Default value at declaration | Yes, through `withInitial` | No |
| Setter on the key | `set`, `remove` | None |
| Typical field | `private static final` | `private static final` or `static final` |
Versions and flags
Scoped values were not a final feature when they first appeared. They were an incubator API in JDK 20, then a preview API from JDK 21 through JDK 24, and they became final in JDK 25. On a preview release you must opt in at both compile time and run time.
Without the flag on a preview JDK, the compiler reports that ScopedValue is a preview API and is disabled by default.
Common declaration mistakes
- Non-static field. Each instance gets its own key, so bindings made through one instance are invisible through another.
- Key created per call. Calling
newInstance()inside a method makes a key nobody else holds. - Missing
final. Reassigning the field later silently switches to a different key, and existing bindings stop matching. - Mutable type argument.
ScopedValue<List<String>>lets any reader modify the shared list. Prefer immutable types or copies. - Expecting a default. Code that calls
get()with no binding in place throws, so bind at the entry point of each request or task.
Exercise
A teammate writes ScopedValue<String> user = ScopedValue.newInstance(); as an instance field in a service class. A request handler in another class binds a value through one service instance, and a helper reads it through a different instance. What does the helper see, and what is the fix?
Show answer
The helper sees an unbound value. isBound() returns false, get() throws NoSuchElementException, and orElse(...) returns its default. Each instance created its own key, and a binding applies only to the key it was made with. The fix is to declare the field static final so that every class shares one key. To limit who can bind it, make it private and expose a runAs-style method and a read accessor.
Exercise
You declare private static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance(); and call REQUEST_ID.orElse(-1) in main without binding anything. What is printed, and why doesn't the declaration alone give the value a default?
Show answer
It prints -1. The declaration creates only a key, and nothing is bound to it, so orElse returns the supplied fallback. A scoped value has no declaration-time default and no setter. Values come only from a where(...).run(...) scope.