Sub topic 2
Reading the Current Value
This chapter assumes core Java syntax, lambdas, and basic thread concepts. A ScopedValue is an immutable value available during a bounded call. Code deeper in that call can read it without receiving it as a parameter.
Reading a bound value
Call get() when the value must be present. Use isBound() to test availability, orElse() for a default, and orElseThrow() for a clear failure.
public class ReadValues {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
System.out.println(USER.isBound()); // false
System.out.println(USER.orElse("anonymous")); // anonymous
ScopedValue.where(USER, "alice").run(() -> {
System.out.println(USER.get()); // alice
System.out.println(USER.orElse("unknown")); // alice
System.out.println(USER.orElseThrow(
() -> new IllegalStateException("User is required")));
});
}
}When no value is bound
Calling get() when USER is unbound throws NoSuchElementException. Choose orElse() when an unbound value is normal. Choose orElseThrow() when continuing without the value is a programming or application error.
Nested scopes and rebinding
An inner binding temporarily shadows an outer binding. When the inner run finishes, the outer value becomes visible again.
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
});Binding several values
Chain where calls before run to create one scope containing several values.
static final ScopedValue<Integer> REQUEST_ID = ScopedValue.newInstance();
ScopedValue.where(USER, "alice")
.where(REQUEST_ID, 42)
.run(() -> System.out.println(
USER.get() + " request #" + REQUEST_ID.get()));The bindings last only for the call to run. The values themselves should be treated as read-only context.
Exercise
What does the final print statement produce after an inner scope binds USER to "admin" and ends?
Show answer
It reads the restored outer value, "alice".