Sub topic 5
Binding a value for the duration of a call
This chapter assumes you know Java lambdas and functional interfaces, the call stack, and static final fields. You should also have declared a ScopedValue, as covered in the previous chapter. Here you will learn how a value gets attached to a call, how long it stays attached, and what the binding does and does not allow.
Declaring is not binding
A ScopedValue<T> field is a key. Declaring it creates no value, and nothing is stored in it yet:
static final ScopedValue<String> USER = ScopedValue.newInstance();A value exists only while some code runs inside a binding. You create a binding in two steps:
ScopedValue.where(key, value)pairs a key with a value. It returns aScopedValue.Carrier, which is a pending binding that holds one or more key and value pairs.- A method on the carrier, such as
runorcall, executes your code with that pairing active.
Until step 2 starts running your code, no code sees the value. The carrier is just a description of what will be bound.
Running code with `run`
Carrier.run(Runnable) executes the runnable with the binding active. Anything the runnable calls, directly or indirectly, can read the value:
public class RequestContext {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> handle());
System.out.println("After run, bound? " + USER.isBound());
}
static void handle() {
audit();
}
static void audit() {
System.out.println("Handling request for " + USER.get());
}
}The program prints Handling request for alice and then After run, bound? false.
handle and audit take no parameters, yet audit sees alice. The value travels with the call stack beneath run. Once run returns, the binding is gone.
Returning a result with `call`
run returns nothing. When the scoped code produces a result, use Carrier.call:
public class CallExample {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
String page = ScopedValue.where(USER, "alice")
.call(() -> render());
System.out.println(page);
}
static String render() {
return "<h1>Welcome, " + USER.get() + "</h1>";
}
}The value returned by the lambda becomes the value returned by call. In the first preview releases (Java 21 to 23) call takes a Callable, so it declares throws Exception, and main above must declare it too. In recent releases the parameter is a CallableOp that rethrows only the exception type your lambda throws. The code above compiles on both. The exact API shifted across preview rounds, so check the Javadoc for your JDK.
Chaining `where` calls
where can be called again on a carrier. Each call adds one pair, and the whole group is bound together when you call run or call:
public class TwoBindings {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice")
.where(REQUEST_ID, 42)
.run(() -> System.out.println(USER.get() + " #" + REQUEST_ID.get()));
}
}This prints alice #42. Both bindings start and end at the same moment, so there is no point at which one is bound and the other is not.
What "duration of a call" means
The binding lasts exactly as long as the run or call method is executing. This holds in every exit path:
- A normal return ends the binding.
- An exception thrown by your code ends the binding, and the exception then propagates to the caller.
- You do not need a
try/finallyblock to clean up.
The last point matters. With ThreadLocal, forgetting remove() can leak a value into whatever work the thread does next, which is a real risk in thread pools. A scoped value has no such step to forget. The runtime ends the binding when the scope exits.
public class ExceptionExit {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
try {
ScopedValue.where(USER, "alice").run(() -> {
throw new IllegalStateException("boom");
});
} catch (IllegalStateException e) {
System.out.println("Caught: " + e.getMessage());
}
System.out.println("Bound after failure? " + USER.isBound());
}
}The output is Caught: boom followed by Bound after failure? false.
No setter, by design
A bound scoped value is immutable. The API has no set method. Code deep in the call chain can read USER, but it cannot change what its callers see. This gives you two guarantees:
- Any method that reads the value sees the same value for the whole scope, unless a nested scope rebinds it for its own duration (covered in a later chapter).
- A callee cannot silently change context for its caller or siblings.
If you need a value that changes while the scope runs, a scoped value is the wrong tool. You can bind a mutable object, such as an AtomicInteger, but then the object's state is shared and mutable, and the safety guarantee applies only to the reference. Prefer immutable values such as strings, records, or unmodifiable collections.
The binding is per thread
The binding is visible to the thread that called run, and to code on that thread. It is not copied into threads you start by hand. A new Thread(...) created inside the scope sees USER.isBound() as false. Sharing bindings with child tasks requires structured concurrency, which a later chapter covers. For now, treat the scope as belonging to one thread's call stack.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `where(USER, "alice")` and never calling `run` or `call` | Nothing is bound and nothing runs. The carrier is discarded. | End the chain with `run` or `call`. |
| Reading `USER.get()` outside any scope | `get` throws `NoSuchElementException` because no value is bound. | Check `isBound()`, or use `orElse` with a default. |
| Reading the value inside a `new Thread` | The new thread has no binding. | Pass the value explicitly, or use structured concurrency. |
| Expecting the value to be changeable | There is no setter. | Rebind in a nested scope, or restructure the code. |
| Binding `null` and expecting "unbound" | A bound `null` is still a binding, so `isBound()` is `true`. | Do not use `null` to mean "absent". Leave the key unbound. |
Compiling and running
On Java 25 and later, scoped values are a final feature and need no flags. On Java 21 to 24 the API is a preview feature, so you must enable it. For a single source file on Java 21:
// Shell command, shown here as a comment:
// java --enable-preview --source 21 RequestContext.javaUse the matching release number for your JDK. A later chapter covers versions and flags in detail.
Exercise
Exercise
Predict the output of this program, line by line, and explain why. static final ScopedValue<String> USER = ScopedValue.newInstance(); public static void main(String[] args) { System.out.println(USER.isBound()); try { ScopedValue.where(USER, "alice").run(() -> { System.out.println(USER.get()); throw new RuntimeException("fail"); }); } catch (RuntimeException e) { System.out.println("caught"); } System.out.println(USER.isBound()); }
Show answer
It prints false, alice, caught, false. Before the scope, no value is bound, so isBound is false. Inside run, USER is bound to alice, so get returns it, and then the exception is thrown. The exception propagates out of run and ends the binding, so the catch block runs and prints caught. Afterwards the binding no longer exists, so isBound is false again. No cleanup code was needed.
Exercise
Why does ScopedValue.where(USER, "alice"); alone, as a statement, never make USER.get() succeed anywhere in your program?
Show answer
where only builds a Carrier that describes the pairing. A binding starts only when run, call, or get executes code on the carrier, and it lasts only while that code runs. With no terminating call, nothing executes and nothing is bound.