J.VI · Java 25 practice question
What is printed when this Java 25 program runs?
class Demo {
static final ScopedValue<String> CONTEXT = ScopedValue.newInstance();
static void readKey() {
System.out.println(CONTEXT.get());
}
static void userCode() {
readKey();
}
public static void main(String[] args) {
ScopedValue.where(CONTEXT, "tenant-7").run(() -> userCode());
}
}
Check answer and explanation
Correct answer: tenant-7
Explanation
Because readKey is called within the dynamic extent of the run call, CONTEXT.get() retrieves the bound value tenant-7 and prints it.
Common trap
Returning null is tempting if a developer assumes ScopedValue defaults to null like an uninitialized ThreadLocal, but CONTEXT is bound for the entire call stack inside run. Throwing NoSuchElementException is tempting if someone thinks the binding only applies to the immediate lambda and not nested calls like readKey, yet any method called from run sees the bound value.
Source: JEP 506: Scoped Values — Description
Checked against the cited text on 2026-11-25.