Sub topic 10
Bounded lifetime and immutability
This chapter assumes you can declare a ScopedValue and bind it with where(...).run(...). It also assumes you know the basics of the call stack. It covers the two guarantees that separate scoped values from ThreadLocal: a binding only lives for the duration of a call, and a binding cannot be changed.
A binding lasts as long as the call
ScopedValue.where(USER, "alice").run(task) creates a binding, runs task, and removes the binding when run returns. This happens whether the task returns normally or throws an exception. You never write cleanup code, and you cannot forget it.
public class Lifetime {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println(USER.isBound()); // false
ScopedValue.where(USER, "alice").run(() ->
System.out.println(USER.isBound())); // true
System.out.println(USER.isBound()); // false again
}
}Every method called from inside the lambda sees alice, however deep the call chain goes. Code outside the lambda never sees it.
There is no setter
A ThreadLocal has set and remove, so any code on the thread can change the value. A ScopedValue has neither. Its API has get, isBound, orElse, and orElseThrow, and nothing that writes. If a method reads USER twice, it gets the same value both times, whatever the methods in between do.
The only way to get a different value is a nested binding. As in the earlier chapter on nested scopes, the inner binding shadows the outer one only while the inner run executes. The outer binding is never modified. It is hidden for a while and then visible again.
This gives you two properties:
- Readers can trust the value. No callee can change what its caller bound.
- The scope can be seen in the code. The binding starts and ends at the
runcall, so you can read the lifetime straight from the source.
What "immutable" covers
The immutability applies to the binding, not to the object behind it. If you bind a mutable object, every reader gets the same reference, and any of them can change its contents.
public class Shared {
static final ScopedValue<StringBuilder> LOG = ScopedValue.newInstance();
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
ScopedValue.where(LOG, sb).run(() -> {
LOG.get().append("step 1;");
step2();
});
System.out.println(sb); // step 1;step 2;
}
static void step2() {
LOG.get().append("step 2;");
}
}The binding of LOG never changes, but the StringBuilder does. This is legal, and sometimes useful, but it brings back the shared mutable state that scoped values are meant to avoid. Prefer immutable values such as strings, records, and numbers. If you do bind a mutable object, make sure it is thread-safe whenever other threads can reach it.
Common mistakes
- Expecting a value to survive after
runreturns. It is gone, soget()throwsNoSuchElementExceptionunless you useorElse. - Looking for a
setmethod. To "change" a value, rebind it in a nested scope. - Treating a bound mutable object as if it were immutable.
Exercise
A method binds USER to "alice" with run, and inside the lambda it calls a helper that binds USER to "admin" with its own run. After the helper returns, what does USER.get() return in the original lambda, and why?
Show answer
It returns "alice". The inner binding only shadows the outer one while the inner run executes. Bindings cannot be modified, so when the inner run returns, the outer binding becomes visible again.