Scoped values

A scoped value passes data to code deep in a call chain without adding a parameter to every method. Unlike a ThreadLocal, the value exists only while a specific call runs and cannot be changed, so it can never leak into the next task on the same thread. This page explains the model behind scoped values, shows binding, nesting, inheritance by subtasks, exceptions and nulls, and compares their cost with ThreadLocal.

Contents

What a scoped value is

Server code often needs the current user, tenant or request ID in methods far from where the request arrived. Passing it as a parameter through every layer clutters every signature, including layers that never use it. The traditional alternative, ThreadLocal, stores a value per thread, but it has three design problems:

  • Unconstrained mutation: any code can call set at any time, so it is hard to know who changed a value.
  • Unbounded lifetime: a value stays until remove() is called or the thread dies. In a thread pool, a forgotten remove() leaks the value into the next task.
  • Expensive inheritance: InheritableThreadLocal copies every value into each child thread, which costs memory when millions of virtual threads are created.

A ScopedValue fixes all three by tying a value to a piece of code instead of to a thread. You create a key, usually a static final field, and bind it for the duration of one call: ScopedValue.where(KEY, value).run(...) or .call(...). Any method executed during that call, at any depth, reads the value with KEY.get(). When the call returns, normally or with an exception, the binding is gone. There is no set method.

Underneath, each thread holds a reference to its current set of bindings. where(...).run(...) creates a new small set that points to the previous one, installs it for the call, and restores the previous one in a finally step. Because bindings are immutable, a child thread created by StructuredTaskScope can simply share the parent's set: nothing is copied. The JEP states that get() is often as fast as reading a local variable, whatever the stack depth.

History of scoped values
JDKJEPStatus
20JEP 429Incubator module
21JEP 446Preview
22, 23, 24JEP 464, 481, 487Further previews; the static runWhere and callWhere shortcuts were removed and call got a typed checked exception
25JEP 506Standard; orElse no longer accepts null

The examples were compiled and run on JDK 25. One of them also uses StructuredTaskScope, which is still a preview API in Java 25 and needs --enable-preview; the others need no flags.

Binding a value for one call

In the program, the repository two levels down reads the current user without receiving it as a parameter. The same document ID is opened as "ana" and as "guest", so the service's access check gives two different results from the same code.

Java
import java.util.NoSuchElementException;

public class RequestContext {

    // One shared key; the value lives only inside a where(...).run(...) call
    static final ScopedValue<String> USER = ScopedValue.newInstance();

    // Deep in the call chain, no parameter carries the user
    static class Repository {
        String load(String id) {
            return "doc " + id + " loaded for " + USER.get();
        }
    }

    static class Service {
        private final Repository repo = new Repository();

        String open(String id) {
            if (USER.get().equals("guest") && id.startsWith("private")) {
                return "denied " + id + " for guest";
            }
            return repo.load(id);
        }
    }

    public static void main(String[] args) {
        Service service = new Service();

        ScopedValue.where(USER, "ana").run(() -> {
            System.out.println(service.open("private-7"));
        });
        String result = ScopedValue.where(USER, "guest").call(() -> service.open("private-7"));
        System.out.println(result);

        // Outside any binding the value does not exist
        System.out.println("bound here? " + USER.isBound());
        System.out.println("orElse: " + USER.orElse("nobody"));
        try {
            USER.get();
        } catch (NoSuchElementException e) {
            System.out.println("get() outside a binding: NoSuchElementException");
        }
    }
}

Output:

Output
doc private-7 loaded for ana
denied private-7 for guest
bound here? false
orElse: nobody
get() outside a binding: NoSuchElementException
  • "ana" got the document; "guest" was denied by Service.open, which read the binding with USER.get() just as the repository did.
  • run takes a Runnable and returns nothing; call returns the lambda's result, here the "denied" string.
  • Outside the bindings, isBound() is false, orElse("nobody") returns the fallback, and get() throws NoSuchElementException.

Nested bindings

Code inside a binding can bind the same key again for a narrower call. The inner value applies only during that call, and the outer one returns automatically afterwards. The program binds a role and an indentation depth together by chaining where, and binds both again for an admin task.

Java
public class Rebinding {

    static final ScopedValue<String> ROLE = ScopedValue.newInstance();
    static final ScopedValue<Integer> DEPTH = ScopedValue.newInstance();

    static void log(String msg) {
        System.out.println("  ".repeat(DEPTH.orElse(0)) + "[" + ROLE.get() + "] " + msg);
    }

    static void adminTask() {
        log("running admin task");
    }

    public static void main(String[] args) {
        // Two values bound at once with a chained where
        ScopedValue.where(ROLE, "user").where(DEPTH, 0).run(() -> {
            log("start");
            // A nested binding shadows the outer one for the inner call only
            ScopedValue.where(ROLE, "admin").where(DEPTH, 1).run(Rebinding::adminTask);
            log("back to the outer binding");
        });
    }
}

Output:

Output
[user] start
  [admin] running admin task
[user] back to the outer binding

The admin task ran with role admin at depth 1, so its line is indented by two spaces. The next log line is back to user at depth 0, with no cleanup code: the inner binding ended with its call. This visible start and end in the source is where the name "scoped" comes from.

No leaks between pooled tasks, no inheritance by plain threads

Thread pools reuse threads. The program runs two tasks on a single-thread pool, so both use the same thread. The first sets a ThreadLocal and forgets to remove it, and also binds a scoped value; the second reads both.

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadsAndInheritance {

    static final ScopedValue<String> TENANT = ScopedValue.newInstance();
    static final ThreadLocal<String> TENANT_TL = new ThreadLocal<>();

    public static void main(String[] args) throws Exception {
        // A pool with one thread, so both tasks run on the same thread
        try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
            pool.submit(() -> {
                TENANT_TL.set("acme");                         // forgot remove()
                ScopedValue.where(TENANT, "acme").run(() -> { });
            }).get();
            pool.submit(() -> {
                System.out.println("next task, ThreadLocal:        " + TENANT_TL.get());
                System.out.println("next task, ScopedValue bound: " + TENANT.isBound());
            }).get();
        }

        // A thread started with new Thread does not inherit the binding
        ScopedValue.where(TENANT, "acme").run(() -> {
            Thread child = new Thread(() ->
                    System.out.println("plain child thread sees a binding: " + TENANT.isBound()));
            child.start();
            try {
                child.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println("parent thread still sees: " + TENANT.get());
        });
    }
}

Output:

Output
next task, ThreadLocal:        acme
next task, ScopedValue bound: false
plain child thread sees a binding: false
parent thread still sees: acme
  • The second task found "acme" left in the ThreadLocal by the first. In a web server that is one customer's data showing up in another customer's request. The scoped value was unbound, as it should be, because its binding ended with the first task's run.
  • A thread started with new Thread did not see the parent's binding, while the parent still did. Plain threads and executor tasks can outlive the binding, so they do not inherit it. The same is true of ForkJoinPool and CompletableFuture tasks.

Inheritance by structured subtasks

Subtasks forked inside a StructuredTaskScope do inherit bindings, because the scope guarantees they finish before the owner leaves the scope, and therefore before the binding ends. The program forks two lookups, then repeats the test with a nested rebinding to see which value the subtask gets.

Java
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;

// Needs JDK 25 with --enable-preview: StructuredTaskScope is still a preview API
public class SubtaskInheritance {

    static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();

    static String fetch(String what) {
        // Runs in a separate virtual thread, yet sees the caller's binding
        return what + " for " + REQUEST_ID.get() + " on a virtual thread: "
                + Thread.currentThread().isVirtual();
    }

    public static void main(String[] args) throws InterruptedException {
        ScopedValue.where(REQUEST_ID, "req-17").run(() -> {
            try (var scope = StructuredTaskScope.open()) {
                Subtask<String> user = scope.fork(() -> fetch("user"));
                Subtask<String> orders = scope.fork(() -> fetch("orders"));
                scope.join();
                System.out.println(user.get());
                System.out.println(orders.get());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // Rebinding inside the scope owner is visible to forks made after it
        ScopedValue.where(REQUEST_ID, "outer").run(() ->
                ScopedValue.where(REQUEST_ID, "inner").run(() -> {
                    try (var scope = StructuredTaskScope.open()) {
                        Subtask<String> s = scope.fork(() -> REQUEST_ID.get());
                        scope.join();
                        System.out.println("subtask sees the innermost binding: " + s.get());
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }));
    }
}

Output (JDK 25, compiled with --enable-preview --release 25 and run with --enable-preview):

Output
user for req-17 on a virtual thread: true
orders for req-17 on a virtual thread: true
subtask sees the innermost binding: inner
  • Both subtasks ran on virtual threads, which is what StructuredTaskScope.open() uses by default, and both read "req-17" without any code to pass it.
  • The subtask forked under the nested binding saw "inner", the binding in effect at the moment of fork.
  • Nothing was copied to the child threads: they share the owner's immutable set of bindings. That is why scoped values suit designs with thousands of short subtasks. See structured concurrency for the scope API.

Exceptions, mutable objects and null

Real code throws exceptions and binds objects. The program saves two rows inside bindings, where the second row is empty so save throws a checked IOException, and it binds a mutable audit list and a null.

Java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ErrorsAndValues {

    static final ScopedValue<String> TX = ScopedValue.newInstance();
    static final ScopedValue<List<String>> AUDIT = ScopedValue.newInstance();

    static String save(String row) throws IOException {
        if (row.isEmpty()) {
            throw new IOException("empty row in " + TX.get());
        }
        AUDIT.get().add(TX.get() + ": saved " + row);
        return row.toUpperCase();
    }

    public static void main(String[] args) {
        List<String> audit = new ArrayList<>();

        // call() passes the checked exception through, typed as IOException
        try {
            String r = ScopedValue.where(TX, "tx-1").where(AUDIT, audit).call(() -> save("a"));
            System.out.println("returned " + r);
            ScopedValue.where(TX, "tx-2").where(AUDIT, audit).call(() -> save(""));
        } catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
        System.out.println("after the exception, TX bound: " + TX.isBound());

        // The binding is immutable, but the object it refers to is not
        System.out.println("audit list filled through the binding: " + audit);

        // where() accepts null; get() then returns null and isBound() is true
        ScopedValue.where(TX, null).run(() ->
                System.out.println("bound to null: isBound=" + TX.isBound() + ", get=" + TX.get()));

        // orElse(null) is rejected in Java 25
        try {
            TX.orElse(null);
        } catch (NullPointerException e) {
            System.out.println("orElse(null): NullPointerException");
        }
    }
}

Output:

Output
returned A
IOException: empty row in tx-2
after the exception, TX bound: false
audit list filled through the binding: [tx-1: saved a]
bound to null: isBound=true, get=null
orElse(null): NullPointerException
  • call passed the IOException through with its real type, so a normal catch (IOException e) works. Since Java 23 the lambda for call is a ScopedValue.CallableOp, which declares the exception type; earlier previews wrapped it in a plain Callable that threw Exception.
  • After the exception, TX was no longer bound: the binding ends however the call ends.
  • The binding itself cannot change, but the list it refers to can: "tx-1: saved a" was added through AUDIT.get(). Bind immutable objects when possible, especially when subtasks share the binding.
  • where(TX, null) is accepted: isBound() is true and get() returns null. orElse(null), however, throws NullPointerException in Java 25, which was the one API change made when the feature became final.

How fast are get() and binding?

The program reads a value 50 million times from a call 20 frames deep, once with a scoped value and once with a ThreadLocal, each 3 times after a warm-up round. It then creates one million bindings, each read once. This is a rough comparison on a 2-CPU Linux machine with JDK 25, not a benchmark.

Java
public class LookupSpeed {

    static final ScopedValue<Integer> SV = ScopedValue.newInstance();
    static final ThreadLocal<Integer> TL = new ThreadLocal<>();

    // Reads the value N times from a call 20 frames deep
    static long readScoped(int depth, int n) {
        if (depth > 0) {
            return readScoped(depth - 1, n);
        }
        long sum = 0;
        for (int i = 0; i < n; i++) {
            sum += SV.get();
        }
        return sum;
    }

    static long readThreadLocal(int depth, int n) {
        if (depth > 0) {
            return readThreadLocal(depth - 1, n);
        }
        long sum = 0;
        for (int i = 0; i < n; i++) {
            sum += TL.get();
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {
        int n = 50000000;
        TL.set(1);
        for (int round = 0; round < 2; round++) {          // round 0 is warm-up
            long bestSv = Long.MAX_VALUE;
            long bestTl = Long.MAX_VALUE;
            long sumSv = 0;
            long sumTl = 0;
            for (int run = 0; run < 3; run++) {
                long t0 = System.nanoTime();
                sumSv = ScopedValue.where(SV, 1).call(() -> readScoped(20, n));
                bestSv = Math.min(bestSv, System.nanoTime() - t0);
                t0 = System.nanoTime();
                sumTl = readThreadLocal(20, n);
                bestTl = Math.min(bestTl, System.nanoTime() - t0);
            }
            if (round == 1) {
                System.out.printf("ScopedValue.get  x %,d: sum %,d, best of 3 %,d ms%n", n,
                        sumSv, bestSv / 1000000);
                System.out.printf("ThreadLocal.get  x %,d: sum %,d, best of 3 %,d ms%n", n,
                        sumTl, bestTl / 1000000);
            }
        }

        // Binding cost: a new binding per call
        long t0 = System.nanoTime();
        long total = 0;
        for (int i = 0; i < 1000000; i++) {
            total += ScopedValue.where(SV, i).call(SV::get);
        }
        System.out.printf("1,000,000 where(...).call(...): sum %,d, %,d ms%n", total,
                (System.nanoTime() - t0) / 1000000);
    }
}

Output:

Output
ScopedValue.get  x 50,000,000: sum 50,000,000, best of 3 40 ms
ThreadLocal.get  x 50,000,000: sum 50,000,000, best of 3 57 ms
1,000,000 where(...).call(...): sum 499,999,500,000, 89 ms
  • Both lookups cost around a nanosecond per read in this hot loop, with the scoped value no slower than the ThreadLocal, despite the 20 frames between the binding and the read. Numbers this small mean the JIT optimized both reads heavily, so in practice the lookup cost is not a reason to choose either one.
  • A new binding with where(...).call(...) cost well under a microsecond. Binding once per request or per operation is effectively free.
  • The real saving appears with many threads: a ThreadLocal keeps an entry in every thread's map, and an InheritableThreadLocal is copied into every child. Scoped values allocate nothing per thread.

ScopedValue or ThreadLocal?

ScopedValue and ThreadLocal side by side
ThreadLocalScopedValue
Give it a valueset, any time, by any codeOnly by binding for a call
LifetimeUntil remove() or the thread diesThe duration of run or call
Leaks into the next pooled taskPossibleNot possible
Child threadsCopied by InheritableThreadLocalShared with structured subtasks, no copy
Memory with many virtual threadsOne map entry per threadNothing per thread
AvailableJava 1.2Java 25 (preview in 21 to 24)
  • Use ScopedValue for context that belongs to a request or an operation: user, tenant, request ID, transaction, locale.
  • Keep ThreadLocal for per-thread caches of expensive, non-thread-safe objects, where the value is meant to live as long as the thread. The ThreadLocal page covers that use.
  • Keep passing a parameter when only one or two methods need the value; a hidden dependency is harder to test.
  • Code that must run on Java 21 to 24 can use scoped values only with --enable-preview, and the API differs between those versions.

Scoped values are designed to work with virtual threads.