Sub topic 9
Binding several values together
Real requests carry more than one piece of context. A web handler might need the authenticated user, a request ID for logging, and a tenant name. This chapter shows how to bind several scoped values for one scope. It also covers how a Carrier object works, how partial rebinding behaves, and when a single record is a better design.
This chapter assumes you can already declare a ScopedValue, bind it with where(...).run(...), and read it with get().
Chaining where calls
ScopedValue.where(key, value) does not run anything. It returns a ScopedValue.Carrier, an immutable object that holds key/value pairs. Calling where on a carrier returns a new carrier with one more pair. Nothing is bound until you call run, call, or get on the carrier.
public class ThreeValues {
static final ScopedValue<String> TENANT = ScopedValue.newInstance();
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(TENANT, "acme")
.where(USER, "alice")
.where(REQUEST_ID, 42)
.run(() -> log("handling request"));
}
static void log(String message) {
System.out.println("[" + TENANT.get() + "/" + USER.get()
+ "/#" + REQUEST_ID.get() + "] " + message);
}
}The program prints [acme/alice/#42] handling request. The log method takes no context parameters. Each key keeps its own type, so REQUEST_ID.get() returns an Integer without a cast.
All pairs in a carrier become visible together when the operation starts. All of them disappear together when it ends. No code can observe a state where USER is bound and REQUEST_ID is not, as long as both come from the same carrier.
Carriers are values you can keep
Because a carrier is immutable and does nothing until it runs, you can store it and run it more than once. This is useful when some context is shared across many operations and some varies per operation.
public class ReusableCarrier {
static final ScopedValue<String> TENANT = ScopedValue.newInstance();
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.Carrier base = ScopedValue.where(TENANT, "acme")
.where(USER, "alice");
for (int i = 1; i <= 2; i++) {
int requestId = i;
base.where(REQUEST_ID, requestId)
.run(() -> System.out.println(
TENANT.get() + "/" + USER.get() + "/#" + REQUEST_ID.get()));
}
}
}The output is:
acme/alice/#1
acme/alice/#2base.where(...) does not change base. Each loop pass builds a fresh carrier from it. This is why a carrier is safe to share between threads, and why a framework can build a base carrier once at startup and extend it per request.
Returning a result
run takes a Runnable and returns nothing. If the work produces a value, use get on the carrier with a Supplier.
public class CarrierResult {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
String label = ScopedValue.where(USER, "alice")
.where(REQUEST_ID, 7)
.get(() -> USER.get() + "-" + REQUEST_ID.get());
System.out.println(label); // alice-7
}
}A call method also exists for work that throws checked exceptions. Its exact signature differs between releases, so check the Javadoc for your Java version before relying on it.
Partial rebinding in nested scopes
An inner where(...).run(...) rebinds only the keys it names. Every other key keeps the value from the enclosing scope.
public class PartialRebind {
static final ScopedValue<String> TENANT = ScopedValue.newInstance();
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(TENANT, "acme").where(USER, "alice").run(() -> {
show("outer");
ScopedValue.where(USER, "admin").run(() -> show("inner"));
show("after");
});
}
static void show(String label) {
System.out.println(label + ": " + TENANT.get() + "/" + USER.get());
}
}The output is:
outer: acme/alice
inner: acme/admin
after: acme/aliceInside the inner scope, TENANT is still acme because the inner carrier never mentions it. Only USER is shadowed. When the inner run returns, USER is alice again.
If one carrier maps the same key twice, the later where for that key takes effect. Do not rely on this for readability. If you need to replace a value, do it with a nested scope, where the intent is visible.
Forgetting one of the keys
Binding a subset of the keys your code needs is the most common mistake with multiple bindings. Reading a key that has no binding throws NoSuchElementException.
import java.util.NoSuchElementException;
public class MissingKey {
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").run(() -> {
System.out.println("request id bound? " + REQUEST_ID.isBound()); // false
try {
System.out.println(REQUEST_ID.get());
} catch (NoSuchElementException e) {
System.out.println("REQUEST_ID is not bound");
}
System.out.println(REQUEST_ID.orElse(-1)); // -1
});
}
}The failure happens at the read site, not where you built the carrier. A missing binding in main might only show up three layers down. Two habits reduce this risk:
- Build the carrier in one place, such as a request filter or an entry-point method, so the full set of bindings is visible together.
- Use
orElseonly for values that really are optional. For required values, letget()fail loudly or useorElseThrowwith a clear exception.
Several keys or one record?
Binding many separate scoped values is not always the best design. You can also bind one scoped value that holds a record.
public class RecordContext {
record Context(String tenant, String user, int requestId) {}
static final ScopedValue<Context> CONTEXT = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(CONTEXT, new Context("acme", "alice", 42))
.run(() -> System.out.println(CONTEXT.get().user()));
}
}The trade-offs:
| Approach | Strength | Weakness |
|---|---|---|
| Chained `where` on separate keys | Each key can be rebound on its own. Code reads only what it needs. | A caller can bind some keys and forget others. |
| Stored `Carrier` | Shared context is built once and extended per operation. | The carrier is not typed to a particular set of keys. Nothing checks that it is complete. |
| One record in one key | All fields are always bound together. The compiler checks the shape. | Changing one field means copying the whole record, for example with a `withUser` method. Code that reads the record depends on all its fields. |
A rule of thumb: use separate keys when the values change independently, as with a user that is switched for an admin operation while the tenant stays fixed. Use a record when the values form one unit that is always set together.
Checking your setup
Scoped values were a preview API in Java 21 through 24 and became a final feature in Java 25. On a preview release, compile and run with --enable-preview. A single-file run looks like this (replace 21 with your Java version):
java --enable-preview --source 21 ThreeValues.javaOn Java 25 or later, run the file without any flags. Method details, such as the call signature, changed between preview releases, so use the Javadoc that matches your JDK.
Common mistakes
- Calling
ScopedValue.where(A, a).where(B, b)and never callingrun,call, orget. The carrier is built, but nothing is bound and no code runs. - Expecting a carrier to carry bindings into a thread created with
new Thread. A carrier binds values only for the operation you run on it, in the current thread. Plain new threads do not inherit those bindings. - Rebinding a key in an inner scope and expecting the outer scope to see the change. The outer value returns as soon as the inner
runfinishes.
Exercise
A request handler runs ScopedValue.where(TENANT, "acme").where(USER, "alice").run(() -> { ScopedValue.where(USER, "bob").run(() -> process()); audit(); });. What are TENANT and USER inside process(), and what are they inside audit()?
Show answer
Inside process(), TENANT is "acme" and USER is "bob". The inner carrier rebinds only USER, so TENANT keeps its outer value. Inside audit(), which runs after the inner run returns, TENANT is "acme" and USER is "alice" again.
Exercise
You build ScopedValue.Carrier base = ScopedValue.where(TENANT, "acme"); once at startup. For each request you call base.where(REQUEST_ID, id).run(task). Does base change, and is it safe to do this from many threads at once?
Show answer
base does not change. where returns a new carrier each time and carriers are immutable. Sharing base between threads is safe. Each run call binds its own values for the current thread only.
Exercise
Code inside ScopedValue.where(USER, "alice").run(...) reads REQUEST_ID.get(), but REQUEST_ID was never bound. What happens, and how can the code check first or supply a default?
Show answer
get() throws NoSuchElementException. The code can test REQUEST_ID.isBound() first, or call REQUEST_ID.orElse(defaultValue) to get a default. The fix for a required value is to add .where(REQUEST_ID, ...) to the carrier.