Sub topic 3
Bounded Lifetime and Immutability
Assume core Java, lambdas, threads, and basic ThreadLocal. A scoped value provides immutable context to a call and the methods it invokes.
Lifetime and immutability
A binding exists only while the operation passed to run executes. After run returns, the binding disappears. Code cannot change the binding in place.
public class Lifetime {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() ->
System.out.println(USER.get())); // alice
System.out.println(USER.isBound()); // false
}
}This bounded lifetime makes cleanup automatic. It also prevents a method from accidentally changing shared context for unrelated work.
ScopedValue compared with ThreadLocal
| Property | `ScopedValue` | `ThreadLocal` |
|---|---|---|
| Update model | Bind a value for a scope | Set and remove a value |
| Lifetime | Follows a call boundary | Follows a thread |
| Mutation | Binding is effectively read-only | Value can be replaced |
| Cleanup risk | Low | Forgetting `remove()` can leak context |
Use ThreadLocal when a component truly needs per-thread mutable state. Prefer ScopedValue for request identity, security context, or tracing data that should flow downward but not be changed.
What other threads see
A plain new Thread(...) does not inherit the current scoped bindings. The child must receive needed data explicitly or use an API that defines context propagation.
Structured concurrency can propagate scoped values to forked subtasks. A child task sees the binding while it runs, and the binding ends with the structured operation.
Virtual threads and migration
Scoped values fit virtual threads because they avoid keeping mutable thread-local state attached to many lightweight threads. They also make context flow explicit through lexical call boundaries.
To migrate from ThreadLocal:
- Declare a
static final ScopedValue. - Replace
setandremovewithScopedValue.where(...).run(...). - Replace
getwithget,orElse, ororElseThrow. - Remove code that mutates the context.
Pitfalls and design guidance
Do not call get() unless a binding is guaranteed. Use isBound or a default when absence is valid. Keep scopes narrow, avoid hiding ordinary method inputs, and remember that plain threads do not inherit bindings.
Exercise
A request binds USER to "alice", then starts a plain new Thread. What does USER.isBound() return in that thread?
Show answer
false. Plain threads do not inherit scoped-value bindings.