Sub topic 10
Bounded lifetime and immutability
This chapter assumes you can read lambdas and Runnable, and that you know how static final fields and the call stack work. It also assumes you have already seen ScopedValue.where(...).run(...) in earlier chapters. Here you learn two rules that define scoped values: a binding exists only while a call runs, and a binding cannot be changed while it exists.
Bounded lifetime
A ScopedValue has no value of its own. A value is attached to it only while a run call is executing. When that call ends, the binding disappears. The part of the program where the binding is visible is the scope.
public class Lifetime {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println("before: " + USER.isBound());
ScopedValue.where(USER, "alice").run(() ->
System.out.println("inside: " + USER.get()));
System.out.println("after: " + USER.isBound());
try {
ScopedValue.where(USER, "alice").run(() -> {
throw new IllegalStateException("boom");
});
} catch (IllegalStateException e) {
System.out.println("after exception: " + USER.isBound());
}
}
}The program prints:
before: false
inside: alice
after: false
after exception: falseThe last line shows that the exception does not leave a binding behind. The runtime removes the binding when run exits, whether it returns normally or throws. You write no try/finally block and you cannot forget a cleanup step.
The scope also follows the call stack. Every method called from inside run sees the binding, however deep the call goes. Code outside run never sees it.
Why a bounded lifetime matters
ThreadLocal has a different lifetime. A value set with ThreadLocal.set stays until someone calls remove or the thread ends. In a thread pool, threads are reused, so a forgotten remove can leak one request's data into the next request on the same thread. That is a correctness bug and a security risk.
A scoped value cannot leak this way because the end of the scope is tied to the end of a method call. You can answer "where is this value visible?" by reading the code. It is visible inside the lambda passed to run, and in whatever that lambda calls.
This also helps the runtime. When it enters a scope it knows exactly when the binding ends, so it can store bindings cheaply and discard them in one step.
Immutability
A scoped value has no set method. Once where(USER, "alice") has bound the value for a scope, nothing in that scope can replace it. This code does not compile:
USER.set("bob"); // compile error: ScopedValue has no set methodImmutability gives you three guarantees:
- Stable reads. Two calls to
USER.get()in the same scope return the same reference. A method deep in the call chain cannot change what its callers will see. - No hidden writes. With
ThreadLocal, any code on the thread can callset. With a scoped value, the only place a value is chosen is thewherecall at the top of the scope. - Predictable data flow. Information moves from the caller down to the callee. Callees cannot send data back up through the context.
Immutable binding, not immutable object
The immutability applies to the binding, not to the object the binding refers to. If you bind a mutable object, callees can still change that object.
import java.util.ArrayList;
import java.util.List;
public class MutableContents {
static final ScopedValue<List<String>> LOG = ScopedValue.newInstance();
public static void main(String[] args) {
List<String> messages = new ArrayList<>();
ScopedValue.where(LOG, messages).run(() -> {
step1();
step2();
});
System.out.println(messages);
}
static void step1() { LOG.get().add("step1"); }
static void step2() { LOG.get().add("step2"); }
}This prints [step1, step2]. The binding to messages never changed, but the list did. The code works, but it brings back the hidden writes that immutability was meant to remove. It is also unsafe if more than one thread ever shares that list.
The following table summarizes what is fixed and what is not.
| Aspect | Fixed during the scope? | Notes |
|---|---|---|
| Which object `get()` returns | Yes | No `set` method exists |
| Fields of that object | Only if the class is immutable | Records with immutable components are a good fit |
| Visibility of the binding | Yes | Limited to the `run` call and what it calls |
| Value in a nested scope | Can differ | A nested `where` creates a new binding, as described below |
Changing a value by rebinding
If the value cannot be changed, how do you give a callee a different one? You open a nested scope with a new binding. The new binding hides the outer one only while the nested run executes. When the nested call ends, the outer value is visible again.
public class Rebinding {
record Session(String user, boolean admin) {}
static final ScopedValue<Session> SESSION = ScopedValue.newInstance();
public static void main(String[] args) {
Session alice = new Session("alice", false);
ScopedValue.where(SESSION, alice).run(() -> {
report("start");
ScopedValue.where(SESSION, new Session(alice.user(), true))
.run(() -> report("elevated"));
report("end");
});
}
static void report(String label) {
Session s = SESSION.get();
System.out.println(label + ": " + s.user() + " admin=" + s.admin());
}
}The output is:
start: alice admin=false
elevated: alice admin=true
end: alice admin=falseThe end line shows that the outer Session was never altered. The elevated session was a separate object, visible only inside the inner scope. A callee that needs a modified context cannot change the caller's view. It can only run further work inside a new scope.
This is why rebinding is the replacement for set. The caller decides when the changed value begins and ends, and the end is automatic.
Reading outside the lifetime
The bounded lifetime has one consequence you must handle. Code that can be called both inside and outside a scope has to cope with the value being absent. Calling get() on an unbound scoped value throws NoSuchElementException. Your options are:
isBound()to check first.orElse(default)to supply a fallback.orElseThrow(supplier)to throw an exception of your choice.
public class Fallback {
static final ScopedValue<String> USER = ScopedValue.newInstance();
static String currentUser() {
return USER.orElse("anonymous");
}
public static void main(String[] args) {
System.out.println(currentUser()); // anonymous
ScopedValue.where(USER, "alice").run(() ->
System.out.println(currentUser())); // alice
System.out.println(currentUser()); // anonymous
}
}The last line prints anonymous again because the scope has ended.
Lifetime and other threads
The scope belongs to the thread that called run. A thread started with new Thread(...) inside the scope does not receive the binding. It can also outlive the scope, and a scoped value must never be visible after its scope ends. Chapter 12 covers how structured concurrency lets forked subtasks share bindings safely, because it guarantees that the subtasks finish before the scope does.
Design guidance from these two rules
- Bind at the edge of your system, for example where a request enters. Bind once, in one place.
- Choose immutable types for the bound value. A record is usually the best choice.
- To change context for a part of the work, wrap that part in a nested
where(...).run(...). Do not try to share a mutable object. - In a method that may run with no scope, use
orElseorisBound. In a method that requires a scope, useget()ororElseThrowso a missing binding fails loudly.
Exercise
A scoped value USER is bound to "alice" with where(USER, "alice").run(...). Inside the lambda, a helper method throws an unchecked exception that nobody catches inside the lambda. After the exception propagates out of run and is caught in main, what does USER.isBound() return, and why?
Show answer
It returns false. The binding lasts only while run executes, and the runtime removes it when run exits, whether normally or by an exception. No try/finally or remove call is needed.
Exercise
You bind a ScopedValue<List<String>> to a new ArrayList and call a method that does LOG.get().add("x"). Is this a violation of scoped value immutability? What would you change so callees cannot modify the list?
Show answer
It is not a violation. The binding (which list LOG refers to) is unchanged, but the list itself is mutable. To prevent changes, bind an unmodifiable list such as List.copyOf(items), or use a record with immutable components.
Exercise
Inside a scope where USER is "alice", you need one callee to run as "admin" without affecting the rest of the scope. There is no set method. How do you do it?
Show answer
Open a nested scope: ScopedValue.where(USER, "admin").run(() -> callee()). The inner binding hides "alice" only while the nested run executes. Afterwards USER.get() returns "alice" again.