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 exceptions propagate up the call stack. Here you will see what a read does when no binding is active, which methods let you handle that case, and the situations that produce it.
A scoped value starts out unbound
A ScopedValue is only a key. It holds no value until some caller binds one. A binding lasts for the duration of one run or call. Any read made outside that dynamic extent finds nothing. We call that state unbound.
The default read is get(). On an unbound scoped value it throws java.util.NoSuchElementException.
import java.util.NoSuchElementException;
public class UnboundGet {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
try {
System.out.println(USER.get());
} catch (NoSuchElementException e) {
System.out.println("No user bound: " + e.getClass().getSimpleName());
}
}
}The program prints No user bound: NoSuchElementException. The exception is unchecked, so the compiler does not force you to handle it. The failure shows up at run time, usually far from the code that forgot to bind the value.
Four ways to read
The same question, "what is the current value?", has four answers depending on how you want to treat the unbound case.
| 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 |
Each method suits a different situation:
get()says "a binding is required here." A missing binding is a programming error, and the exception reports it.isBound()is a test. Use it when the two cases take different code paths, such as skipping an audit log entry when nobody is logged in.orElse(other)supplies a default. It fits cases where a missing value is normal, such as an anonymous user.orElseThrow(supplier)isget()with an exception type and message you choose. It gives callers a clearer failure than a bareNoSuchElementException.
public class FourReads {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
// Outside any binding
System.out.println(USER.isBound()); // false
System.out.println(USER.orElse("anonymous")); // anonymous
try {
USER.orElseThrow(() -> new IllegalStateException("No user in scope"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // No user in scope
}
// Inside a binding
ScopedValue.where(USER, "alice").run(() -> {
System.out.println(USER.isBound()); // true
System.out.println(USER.get()); // alice
System.out.println(USER.orElse("anonymous")); // alice
System.out.println(USER.orElseThrow(
() -> new IllegalStateException("No user in scope"))); // alice
});
}
}orElse and orElseThrow do not change the binding. They only decide what you get back when there is none.
Where unbound reads come from
Unbound reads are rarely a typo in the read itself. They come from code running outside the dynamic extent of a binding. Three situations cover most cases.
Code that runs before or after the scope
The binding exists only while run or call executes. A read before it starts or after it returns sees nothing. The outer scope is not affected by this. In a nested binding, the outer value comes back when the inner scope ends, as you saw in the chapter on nesting. Only a scope with no outer binding returns to the unbound state.
public class AfterScope {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "alice").run(() ->
System.out.println("inside: " + USER.get()));
System.out.println("after: " + USER.isBound()); // false
}
}The program prints inside: alice and then after: false.
Code that runs on another thread
Bindings belong to the thread that established them. A plain new Thread(...) does not inherit them, so the new thread reads an unbound value. The same applies to tasks you submit to an ordinary ExecutorService. Those tasks run on pool threads that never saw your where(...).run(...) call.
import java.util.NoSuchElementException;
public class OtherThread {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) throws InterruptedException {
ScopedValue.where(USER, "alice").run(() -> {
Thread t = new Thread(() -> {
try {
System.out.println(USER.get());
} catch (NoSuchElementException e) {
System.out.println("worker: unbound");
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}The worker prints worker: unbound, even though the code that created it was inside a binding. Structured concurrency, covered in a later chapter, is the supported way to carry bindings to forked subtasks.
Code that is called from an entry point nobody wrapped
A library method may call USER.get() and work in every test that binds a user. In production, a path such as a scheduled job, a startup hook, or a message listener may reach the same method without a binding. The read is correct only for callers that bound the value. This is the most common source of unbound failures in real applications.
Reading a bound `null`
You can bind null as a value: ScopedValue.where(USER, null). In that case the scoped value is bound, but its value is null. isBound() returns true, and get() returns null without throwing.
public class BoundNull {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, (String) null).run(() -> {
System.out.println(USER.isBound()); // true
System.out.println(USER.get()); // null
System.out.println(USER.orElse("anonymous")); // null
});
}
}The last line surprises many readers. orElse supplies its default only when there is no binding. A bound null is still a binding, so orElse returns null. If null is not meaningful for your data, do not bind it. Prefer Optional<T> as the scoped value's type, or bind a real "anonymous" object.
Choosing a strategy
The decision flow below shows how to pick a read method.
Some practical guidance follows from this:
- Fail early at the boundary. Where a request enters your system, bind the value once. Deeper code can then use
get()and treat an exception as a real bug. - Use
orElseThrowat API edges. A message such as "No tenant in scope; wrap the call in TenantContext.runAs" is far easier to act on than a bareNoSuchElementException. - Use
orElsesparingly. A default can hide a missing binding. A job that silently runs as "anonymous" may write data under the wrong identity. - Do not poll with
isBound()and thenget()in a loop. Within one thread, a binding cannot change while the scope runs, so a single check is enough. There is no race between the check and the read.
Java version note
Scoped values were a preview API in Java 21 and several releases after it. They became a final feature in Java 25. On a preview release you must compile and run with --enable-preview, for example java --enable-preview --source 21 UnboundGet.java. On Java 25 or later no flag is needed. The unbound behavior described here is the same across these releases. Without the flag on a preview release, the compiler rejects the code before any read can happen.
Exercise
A method contains String user = USER.orElse("anonymous");. It is called inside ScopedValue.where(USER, (String) null).run(...). What does user contain, and why? How would you get "anonymous" in that case?
Show answer
user is null. The scoped value is bound (to null), and orElse returns its default only when there is no binding at all. To get "anonymous", either do not bind null (bind "anonymous" or leave the value unbound), or check explicitly: String user = USER.isBound() && USER.get() != null ? USER.get() : "anonymous";.
Exercise
Code inside ScopedValue.where(USER, "alice").run(...) submits a task to a plain Executors.newFixedThreadPool(2) pool. The task calls USER.get(). What happens, and why?
Show answer
The task throws NoSuchElementException. Bindings are tied to the thread that established them and are not copied to pool threads, so USER is unbound there. To pass the value, read it before submitting and give it to the task as a parameter, or use structured concurrency so that forked subtasks inherit the binding.