Sub topic 8
Nested scopes and temporary rebinding
This chapter assumes you can bind and read a ScopedValue with ScopedValue.where(...).run(...). It also assumes you know lambdas and the call stack. On Java 21 to 24, scoped values are a preview API. Compile and run with --enable-preview. Later releases may not need the flag, so check your JDK.
Rebinding inside a scope
A binding lasts for the duration of one run call. You can start another where(...).run(...) inside that call, using the same ScopedValue with a different value. Inside the inner call, get() returns the new value. When the inner call returns, the outer value is visible again.
public class Nested {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
System.out.println(USER.get()); // alice
ScopedValue.where(USER, "admin").run(() ->
System.out.println(USER.get())); // admin
System.out.println(USER.get()); // alice again
});
}
}The program prints alice, admin, alice.
The inner binding does not change the outer one. It shadows the outer binding for as long as the inner run is executing. Nothing is assigned, and nothing needs to be undone.
Callees see the nearest binding
Rebinding also reaches the methods you call. Any method called from inside the inner scope sees the inner value, even though it takes no parameter.
public class Audit {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() -> {
log("start");
ScopedValue.where(USER, "admin").run(() -> log("cleanup"));
log("end");
});
}
static void log(String step) {
System.out.println(step + " by " + USER.get());
}
}The output is:
start by alice
cleanup by admin
end by aliceThe method log is identical in all three calls. Only the binding on the call stack changes. This makes temporary elevation of privileges easy to write, and it can be confined to a few lines of code.
Restoration is automatic
The outer value comes back when the inner run ends. That holds if the inner code finishes normally and if it throws an exception. You do not need a try/finally block to restore it. This is a key difference from ThreadLocal, where you must call set and then restore the old value yourself.
Common mistakes
- Expecting an assignment.
ScopedValuehas nosetmethod. To get a new value, open a new scope. - Leaking the inner value. Code that runs after the inner
runreturns sees the outer value. Do not rely on the inner value being visible there. - Rebinding in other threads. A thread started with
new Threaddoes not inherit your bindings, so nesting does not help there. A later chapter covers this.
Exercise
Exercise
What does this program print? static final ScopedValue<Integer> LEVEL = ScopedValue.newInstance(); ScopedValue.where(LEVEL, 1).run(() -> { ScopedValue.where(LEVEL, 2).run(() -> { ScopedValue.where(LEVEL, 3).run(() -> System.out.print(LEVEL.get() + " ")); System.out.print(LEVEL.get() + " "); }); System.out.print(LEVEL.get()); });
Show answer
It prints "3 2 1". Each inner scope shadows the previous binding only while it runs. When the level 3 scope ends, level 2 is visible again. When the level 2 scope ends, level 1 is visible again.