Sub topic 6
Reading the current value
This chapter assumes you can declare a ScopedValue and bind it with ScopedValue.where(...).run(...). It also assumes you know that a binding lasts only while the run call executes.
Four ways to read
A ScopedValue has four read methods. They differ only in what happens when no binding is in effect.
| Method | Bound | Unbound |
|---|---|---|
| `get()` | Returns the value | Throws `NoSuchElementException` |
| `isBound()` | Returns `true` | Returns `false` |
| `orElse(other)` | Returns the value | Returns `other` |
| `orElseThrow(supplier)` | Returns the value | Throws the exception the supplier creates |
The method reads the binding of the nearest enclosing scope on the current thread. It does not matter how deep in the call stack the read happens.
A runnable example
import java.util.NoSuchElementException;
public class Reading {
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
try {
USER.get();
} catch (NoSuchElementException e) {
System.out.println("get() failed: nothing bound");
}
try {
USER.orElseThrow(() -> new IllegalStateException("No user in scope"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
ScopedValue.where(USER, "alice").run(() -> {
System.out.println(USER.isBound()); // true
System.out.println(USER.get()); // alice
});
}
}On Java 21 through 24 the API is a preview feature. Compile and run with --enable-preview and a matching --release, for example javac --release 24 --enable-preview Reading.java and then java --enable-preview Reading. Java 25 made it final, so no flag is needed there.
Choosing a method
Use get() when the code cannot work without the value. An unbound read then fails loudly, and you find the missing binding early. This is the usual choice for something like a current user in request-handling code.
Use orElse when a sensible default exists, such as "anonymous" or a default locale. The default is evaluated eagerly, so keep it cheap.
Use orElseThrow when you want a clear domain exception instead of the generic NoSuchElementException. The message can then say what is missing and why it matters.
Use isBound() when you need to branch on whether a scope exists. Avoid the pattern if (X.isBound()) use(X.get()) when orElse would do. It is longer and says the same thing.
Common errors
- Reading outside any scope. Code that works inside
runfails when called from a test or frommainwithout a binding. Bind the value in the test setup, or useorElse. - Reading from another thread. A thread created with
new Threaddoes not inherit bindings. Inside it,isBound()isfalseandget()throws. The value must be bound in that thread's own scope, or shared through structured concurrency, which a later chapter covers. - Reading after the scope ends. The binding disappears when
runreturns. Do not capture the result ofget()in a lambda that runs later and expectUSERto still be bound. Read the value inside the scope and pass the plain value along. - Expecting a write. A
ScopedValuehas noset. To change what callees see, open a nested scope with a newwhere.
Exercise
A helper method calls USER.get() and is invoked from a unit test with no surrounding where(...).run(...). What happens, and what are two ways to fix it?
Show answer
It throws NoSuchElementException because USER is unbound. One fix is to run the test body inside ScopedValue.where(USER, "test-user").run(...). The other is to change the helper to use USER.orElse("anonymous") or USER.orElseThrow(...) with a clearer exception.
Exercise
Inside a bound scope, you start a plain new Thread(...) that calls USER.isBound(). What does it return, and why?
Show answer
It returns false. Scoped value bindings are not inherited by threads created with new Thread, so the new thread has no binding for USER.