Sub topic 8
Nested Scopes and Temporary Rebinding
This chapter assumes you can declare a ScopedValue and bind it with ScopedValue.where(...).run(...). It also assumes you can read the value with get, and that you are comfortable with lambdas and the call stack. If the feature is still a preview API in your JDK, compile and run with --enable-preview and a matching --release value. Java 25 and later need no flag.
Binding is a scope, not an assignment
A scoped value has no setter. You cannot change USER from "alice" to "admin" while code is running. You can only run a new piece of code inside a new binding. The new binding shadows the old one for as long as that code runs. When the code finishes, the old binding is visible again.
This lets you change a value for a bounded region of code, such as one privileged operation. Nothing needs to be restored by hand afterwards.
The basic pattern
public class Rebinding {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
report("start");
runAsAdmin(() -> report("inside"));
report("end");
});
}
static void runAsAdmin(Runnable action) {
ScopedValue.where(USER, "admin").run(action);
}
static void report(String label) {
System.out.println(label + ": " + USER.get());
}
}The output is:
start: alice
inside: admin
end: aliceThe lambda () -> report("inside") is written inside the alice scope, but it prints admin. A scoped value is resolved when get is called, by looking at the bindings active on the current call stack. Where the lambda was written does not matter. What matters is which run call is executing it. This is dynamic scoping. It is different from how local variables and captured lambda variables behave.
The diagram shows the bindings that are active at each point.
What a nested scope sees
The following rules cover every case.
| Situation | What `get()` returns |
|---|---|
| Directly in the outer scope, before the inner scope starts | Outer value |
| Inside the inner scope, in your own code | Inner value |
| Inside a method called from the inner scope, however deep | Inner value |
| Back in the outer scope after the inner `run` returns | Outer value |
| Inside the inner scope, for a key the inner scope did not rebind | Whatever the outer scope bound |
The last row matters in larger programs. Rebinding one key leaves every other binding in place.
public class PartialRebinding {
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, 1).run(() -> {
show("outer");
ScopedValue.where(REQUEST_ID, 2).run(() -> show("inner"));
show("outer again");
});
}
static void show(String label) {
System.out.println(label + ": " + USER.get() + " #" + REQUEST_ID.get());
}
}The output is:
outer: alice #1
inner: alice #2
outer again: alice #1The inner scope rebinds only REQUEST_ID, so USER is still alice inside it. You do not need to repeat bindings you want to keep.
Restoration is automatic, including on exceptions
The outer binding returns when the inner run ends, and that includes an abrupt end. You do not need a try/finally block, which ThreadLocal code needs when it sets and then resets a value.
public class RestoreOnException {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
try {
ScopedValue.where(USER, "admin").run(() -> {
throw new IllegalStateException("boom");
});
} catch (IllegalStateException e) {
System.out.println("caught " + e.getMessage() + ", user is " + USER.get());
}
});
}
}The output is caught boom, user is alice. The unchecked exception propagates out of the inner run. By the time the catch block runs, the inner binding is already gone.
A ThreadLocal version must save the old value and restore it in finally. If someone forgets, the wrong user stays attached to the thread. This is the main reason nested rebinding is safer with scoped values.
Returning a result from an inner scope
run takes a Runnable, so it returns nothing. When the inner scope has to produce a value, use call, which takes a Callable.
import java.util.concurrent.Callable;
public class InnerResult {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws Exception {
String result = ScopedValue.where(USER, "alice").call(() -> {
String elevated = ScopedValue.where(USER, "admin")
.call(() -> "ran as " + USER.get());
return elevated + ", back to " + USER.get();
});
System.out.println(result);
}
}The output is ran as admin, back to alice. call declares throws Exception, so the caller must handle checked exceptions. Use run when you have no result, because it adds no throws clause.
Reusing a binding
ScopedValue.where(USER, "alice") returns a carrier object. A carrier holds bindings but does nothing until you call run or call on it. You can keep one and use it more than once, or extend it with more where calls.
public class CarrierReuse {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static final ScopedValue<String> ROLE = ScopedValue.newInstance();
public static void main(String[] args) {
var base = ScopedValue.where(USER, "alice");
base.where(ROLE, "reader").run(() -> print());
base.where(ROLE, "editor").run(() -> print());
}
static void print() {
System.out.println(USER.get() + " as " + ROLE.get());
}
}The output is:
alice as reader
alice as editorAdding where(ROLE, ...) to base returns a new carrier each time. The original base is unchanged. This also settles a question about duplicate keys. If one chain binds the same key twice, as in where(USER, "a").where(USER, "b"), the later binding takes precedence inside that single scope.
Edge cases
- Rebinding to the same value is allowed and has no visible effect. It is still a new scope, so the binding ends when that
runreturns. - Binding
nullis allowed.USER.get()then returnsnull, andisBound()istrue. The key counts as bound even when the value isnull. - Nesting depth has no practical limit. Each level shadows the one before it, and leaving a level restores the previous one.
- Threads are a separate matter. A binding does not follow you into a plain
new Thread, so a nested scope in the parent is not visible there either. A later chapter covers sharing bindings with forked subtasks.
Design guidance
Use nested rebinding for a temporary change of context: acting on behalf of another user, tagging a sub-operation with its own request ID, or running a step with a different tenant. Prefer a narrow run around only the code that needs the change. When you reach for an inner scope, check that the value really is context for everything called beneath it. If only one method needs it, a parameter is clearer.
Exercise
Predict the output of this program, then explain why the third line differs from the second. static final ScopedValue<String> USER = ScopedValue.newInstance(); static final ScopedValue<Integer> LEVEL = ScopedValue.newInstance(); static void p(String s) { System.out.println(s + " " + USER.get() + " " + LEVEL.get()); } public static void main(String[] args) { ScopedValue.where(USER, "alice").where(LEVEL, 1).run(() -> { p("a"); ScopedValue.where(LEVEL, 2).run(() -> { p("b"); ScopedValue.where(USER, "bob").run(() -> p("c")); }); p("d"); }); }
Show answer
The output is "a alice 1", "b alice 2", "c bob 2", "d alice 1". At "b" only LEVEL is rebound, so USER is still alice. At "c" the innermost scope rebinds USER to bob, while LEVEL remains 2 because that scope did not rebind it. At "d" both inner scopes have ended, so the original bindings alice and 1 are restored.
Exercise
A colleague writes a helper that saves the current user into a local variable, runs a task inside ScopedValue.where(USER, "admin").run(task), and then "restores" the user in a finally block. Why is the finally block unnecessary?
Show answer
The binding made by where(...).run(...) lasts only while run executes. When run returns, normally or with an exception, the runtime removes the inner binding and the outer one is visible again. There is nothing to restore, and USER has no setter, so the finally block could not assign to it anyway.