Sub topic 6
Reading the current value
This chapter covers the four ways to read a scoped value and what each one does when no value is bound. It assumes you can declare a ScopedValue and bind it with where(...).run(...), as in the earlier chapters. It also assumes you know what a lambda is and what the call stack is.
Reading is always relative to the current scope
A ScopedValue object is a key. It does not hold the value itself. When code calls a read method on the key, the runtime looks up the binding that is active for the current thread, at that point in the call stack.
This is why the same static final field can return different results in different places:
- Inside
where(USER, "alice").run(...),USERreads as"alice". - Inside a nested
where(USER, "admin").run(...), it reads as"admin". - Outside every binding, it has no value.
The reading code never says which scope it expects. It only asks the key for the value that applies right now.
The four read methods
ScopedValue<T> has four read methods. All are instance methods called on the key.
| Method | If a value is bound | If nothing is bound |
|---|---|---|
| `get()` | Returns the value | Throws `NoSuchElementException` |
| `isBound()` | Returns `true` | Returns `false` |
| `orElse(T other)` | Returns the bound value | Returns `other` |
| `orElseThrow(Supplier<? extends X>)` | Returns the bound value | Throws the exception the supplier creates |
get()
Use get() when a missing value means the program has a bug. For example, a method that needs the current user should fail loudly if it was called outside a request scope.
static void audit(String action) {
System.out.println(USER.get() + " did " + action);
}get() has no null fallback. An unbound read raises NoSuchElementException, so the mistake shows up at once and not later as a NullPointerException somewhere else.
isBound()
isBound() answers one question: is there a binding in the current scope? Use it when your code has two legitimate paths, with a value and without one.
orElse(other)
orElse gives a default without a separate check. It suits optional context, such as a display name that falls back to "anonymous".
orElseThrow(supplier)
orElseThrow also fails when the value is missing, but you choose the exception and its message. Prefer it over get() at API boundaries, where a clear message such as "No user bound; call this inside a request scope" helps the next developer.
Putting them together
This program reads the same key outside and inside a binding. It runs on Java 25 without flags. On Java 21 to 24 it needs preview flags, covered below.
import java.util.NoSuchElementException;
public class ReadingValues {
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.get();
} catch (NoSuchElementException e) {
System.out.println("get() failed: no value bound");
}
try {
USER.orElseThrow(() -> new IllegalStateException("No user bound"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // No user bound
}
// 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 bound"))); // alice
});
}
}The expected output is:
false
anonymous
get() failed: no value bound
No user bound
true
alice
alice
aliceInside the binding, all four methods agree. The difference between them only appears when the value is missing.
Running the example
Scoped values were a preview API in Java 21 through 24 and became final in Java 25. On Java 21 to 24, compile and run with preview enabled. The --source value must match your JDK's feature release:
java --enable-preview --source 21 ReadingValues.javaReplace 21 with 22, 23, or 24 to match your JDK. On Java 25 or later, run java ReadingValues.java. A preview-only class compiled without the flag fails with an error saying the API is a preview API.
Choosing a read method
Edge cases
Checking then reading is safe
With a mutable global, if (x.isSet()) x.get() has a race: another thread could change x between the two calls. A scoped binding is immutable for the whole scope, and it belongs to the current thread's stack. So this is safe:
if (USER.isBound()) {
audit(USER.get());
}Nothing can unbind USER between the two lines. The binding only ends when the enclosing run returns, and that cannot happen while this code is running inside it.
A bound value can be null
You can bind null, for example where(USER, null). In that case isBound() returns true and get() returns null. orElse("anonymous") then returns null, not "anonymous", because the key is bound. The default applies only to unbound keys. If null should mean "no user", do not bind null. Leave the key unbound, or bind a value such as Optional.empty() or a dedicated "anonymous user" object.
Reads see the innermost binding
When scopes are nested, a read returns the innermost binding of that key. Reads of other keys are not affected by a rebinding of this one. The next chapters cover nesting in more detail.
Other threads start unbound
A read in a thread created with new Thread finds no binding, because bindings are not inherited by plain threads. isBound() returns false there and get() throws. If a method reads a scoped value and may run on such a thread, use orElse or isBound, or make sure the caller binds the value first. Structured concurrency, covered later, is the supported way to share bindings with subtasks.
Reads are cheap
A read does not go through a per-thread hash map the way ThreadLocal.get() does. The runtime caches the lookup, so reading in a hot path is fine. You do not need to copy the value into a local variable for speed. You may still want to do it for readability when you use the value several times in one method.
Common errors
- Reading outside any scope. A utility called from
main, or from a test, with no surroundingwhere(...).run(...)throwsNoSuchElementExceptiononget(). Bind a value in the test setup, or read withorElse. - Using
orElseto hide bugs. A default such as"anonymous"can let an unauthenticated path run quietly where you wanted a failure. UseorElseonly when the default is valid behavior. - Calling
get()in a new thread. Code that worked on the request thread fails after you move it tonew Thread(...)or to an executor you did not set up for scoped values. - Expecting a write. There is no
set. To change what code sees, open a nested scope withwhere(...).run(...).
Exercise
A key TENANT is declared as ScopedValue<String>. In main, with no enclosing binding, you run System.out.println(TENANT.orElse("none")); and then System.out.println(TENANT.get());. What does the program print and do? Then you wrap both lines in ScopedValue.where(TENANT, null).run(...). How does the output change?
Show answer
Without a binding, the first line prints none, and the second throws NoSuchElementException because the key is unbound. With where(TENANT, null), the key is bound to null, so orElse("none") returns null and prints null, and get() returns null and prints null, with no exception.
Exercise
Write a method String describeUser() that returns "guest" when USER is unbound and "user:" + name when it is bound. Name two ways to write it, and say which one reads better.
Show answer
One way is return USER.isBound() ? "user:" + USER.get() : "guest";. The other is return USER.isBound() ? "user:" + USER.get() : "guest"; replaced by return "user:" + USER.orElse("guest");, but that gives "user:guest", which is wrong. The correct second form is String name = USER.orElse(null); return name == null ? "guest" : "user:" + name;. The isBound() version reads better because it states the intent directly and does not depend on null as a signal. It is also safe, because the binding cannot change between the check and the read.