With the release of Java 25, scoped values come out of preview and enter the mainstream as one of the most impactful improvements for concurrency and context propagation in Java’s recent history. Designed to address the perennial issue of safely sharing context across method chains and threads, scoped values deliver a clean, immutable, and automatically bounded solution that dethrones the error-prone ThreadLocal for most scenarios.

Rethinking Context: Why Scoped Values?

For years, Java developers have used ThreadLocal to pass data down a call stack—such as security credentials, logging metadata, or request-specific state. While functional, ThreadLocal suffers from lifecycle ambiguity, memory leaks, and incompatibility with lightweight virtual threads. Scoped values solve these problems by making context propagation explicit in syntax, immutable in nature, and automatic in cleanup.

The Mental Model

Imagine code execution as moving through a series of rooms, each with its unique lighting. A scoped value is like setting the lighting for a room—within its boundaries, everyone sees the same illumination (data value), but outside those walls, the setting is gone. Each scope block clearly defines where the data is available and safe to access.

How Scoped Values Work

Scoped values require two ingredients:

  • Declaration: Define a ScopedValue as a static final field, usually parameterized by the intended type.
  • Binding: Use ScopedValue.where() to create an execution scope where the value is accessible.

Inside any method called within the binding scope—even dozens of frames deep—the value can be retrieved by .get(), without explicit parameter passing.

Example: Propagating User Context Across Methods

// Declare the scoped value
private static final ScopedValue<String> USERNAME = ScopedValue.newInstance();

public static void main(String[] args) {
    ScopedValue.where(USERNAME, "alice").run(() -> entryPoint());
}

static void entryPoint() {
    printCurrentUser();
}

static void printCurrentUser() {
    System.out.println("Current user: " + USERNAME.get()); // Outputs "alice"
}

In this sample, USERNAME is accessible in any method within the binding scope, regardless of how far it’s called from the entry point.

Nested Binding and Rebinding

Scoped values provide nested rebinding: within a scope, a method can establish a new nested binding for the same value, which is then available only to its callees. This ensures truly bounded context lifetimes and avoids unintended leakage or overwrites.

// Declare the scoped value
private static final ScopedValue<String> MESSAGE = ScopedValue.newInstance();

void foo() {
    ScopedValue.where(MESSAGE, "hello").run(() -> bar());
}

void bar() {
    System.out.println(MESSAGE.get()); // prints "hello"
    ScopedValue.where(MESSAGE, "goodbye").run(() -> baz());
    System.out.println(MESSAGE.get()); // prints "hello"
}

void baz() {
    System.out.println(MESSAGE.get()); // prints "goodbye"
}

Here, the value "goodbye" is only visible within the nested scope inside baz, while "hello" remains for bar outside that sub-scope.openjdk

Thread Safety and Structured Concurrency

Perhaps the biggest leap: scoped values are designed for modern concurrency, including Project Loom’s virtual threads and Java's structured concurrency. Scoped values are automatically inherited by child threads launched within the scope, eliminating complex thread plumbing and ensuring correct context propagation.

// Declare the scoped value
private static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();

public static void main(String[] args) throws InterruptedException {
    String requestId = "req-789";
    usingVirtualThreads(requestId);
    usingStructuredConcurrency(requestId);
}

private static void usingVirtualThreads(String requestId) {
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        // Launch multiple concurrent virtual threads, each with its own scoped value binding
        Future<?> taskA = executor.submit(() ->
                ScopedValue.where(REQUEST_ID, requestId).run(() -> processTask("Task VT A"))
        );
        Future<?> taskB = executor.submit(() ->
                ScopedValue.where(REQUEST_ID, requestId).run(() -> processTask("Task VT B"))
        );
        Future<?> taskC = executor.submit(() ->
                ScopedValue.where(REQUEST_ID, requestId).run(() -> processTask("Task VT C"))
        );

        // Wait for all tasks to complete
        try {
            taskA.get();
            taskB.get();
            taskC.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

private static void usingStructuredConcurrency(String requestId) {
    ScopedValue.where(REQUEST_ID, requestId).run(() -> {
        try (var scope = StructuredTaskScope.open()) {
            // Launch multiple concurrent virtual threads
            scope.fork(() -> {
                processTask("Task SC A");
            });
            scope.fork(() -> {
                processTask("Task SC B");
            });
            scope.fork(() -> {
                processTask("Task SC C");
            });

            scope.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    });
}

private static void processTask(String taskName) {
    // Scoped value REQUEST_ID is automatically visible here
    System.out.println(taskName + " processing request: " + REQUEST_ID.get());
}

No need for explicit context passing—child threads see the intended value automatically.

Key Features and Advantages

  • Immutability: Values cannot be mutated within scope, preventing accidental overwrite and race conditions.
  • Automatic Cleanup: Context disappears at the end of the scope, eliminating leaks.
  • No Boilerplate: No more manual parameter threading across dozens of method signatures.
  • Designed for Virtual Threads: Plays perfectly with Java’s latest concurrency primitives.baeldung+2

Use Cases

  • Securely propagate authenticated user or tracing info in web servers.
  • Pass tenant, locale, metrics, or logger context across libraries.
  • Enable robust structured concurrency with context auto-inheritance.