Sub topic 7
What happens when no value is bound
This chapter assumes you can declare a ScopedValue and bind it with ScopedValue.where(...).run(...). It also assumes you know that a scoped value is only visible while the run call is executing.
Unbound is a normal state
A ScopedValue has no default value. It is bound only inside a where(...).run(...) call. Outside that call, or in code that no binding scope ever reached, it is unbound. Unbound is an ordinary state. It becomes a bug only when code reads the value as if it were always present.
What `get()` does
Calling get() on an unbound scoped value throws java.util.NoSuchElementException. It does not return null. This is intentional. A missing user or request ID usually means the call path is wrong, and a silent null would hide that.
Four ways to read safely
| Method | When unbound |
|---|---|
| `get()` | Throws `NoSuchElementException` |
| `isBound()` | Returns `false` |
| `orElse(other)` | Returns `other` |
| `orElseThrow(supplier)` | Throws the exception your supplier creates |
Use isBound() when you need to branch on whether a binding exists. Use orElse when a fallback makes sense, such as "anonymous". Use orElseThrow when the value is required and you want an error that explains what is missing.
import java.util.NoSuchElementException;
public class Unbound {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
try {
USER.get();
} catch (NoSuchElementException e) {
System.out.println("get() failed: nothing is bound");
}
System.out.println(USER.isBound()); // false
System.out.println(USER.orElse("anonymous")); // anonymous
try {
USER.orElseThrow(() ->
new IllegalStateException("No user bound; call this inside a request scope"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
ScopedValue.where(USER, "alice").run(() ->
System.out.println(USER.orElseThrow(() ->
new IllegalStateException("No user bound")))); // alice
}
}The first three reads happen outside any binding, so each shows the unbound behavior. The last read is inside a binding and returns alice.
Where unbound access usually comes from
- A new thread. A thread created with
new Threaddoes not inherit bindings, soUSER.isBound()isfalseinside it. The same applies to tasks you hand to an ordinary executor. - Code run outside the scope. A lambda stored and executed after
runreturns finds the binding gone, because the lifetime is bounded. - Tests and entry points. A method you call directly from a test skips the code that normally sets up the binding.
Choosing a strategy
Use orElse only when the default is a safe, meaningful behavior. A default like "anonymous" for logging is reasonable. A default that grants access or writes data is not. For required context, prefer orElseThrow with a message naming the missing value and the expected scope. This gives a better failure than the generic NoSuchElementException from get().
Running the example
Scoped values were a preview API in Java 21 through 24. There you compile and run with preview enabled, for example javac --release 21 --enable-preview Unbound.java and java --enable-preview Unbound. In Java 25 the API is final and needs no flags.
Exercise
A request handler binds USER and starts a plain new Thread that calls USER.get(). What happens in that thread, and what are two ways to make the code behave sensibly?
Show answer
The call throws NoSuchElementException, because a thread created with new Thread does not inherit bindings. You can pass the user to the thread explicitly as a parameter, or call orElse or orElseThrow so the thread handles the missing value deliberately. You can also check isBound() first and branch on the result.