Versioned structured concurrency
What you will learn
Structured concurrency treats related subtasks as part of one owning operation. Java 25 has stable ScopedValue bindings and a fifth-preview StructuredTaskScope API. Learn the lifetime pattern on Java 21 using explicit context and owned futures, then examine the Java 25-specific APIs separately.
- Explain ownership, joining, cancellation and scoped context.
- Distinguish stable and preview features on Java 21 and 25.
- Implement a finite owned task group with cleanup and explicit context.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. The stable examples use finite submissions, cooperative tasks and executor ownership. The fixture runner also enforces a process deadline.
Pass immutable request context explicitly
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { record Request(String id) {} Request request = new Request("R-42"); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { var a = executor.submit(() -> request.id()+":price"); var b = executor.submit(() -> request.id()+":stock"); System.out.println(a.get(3, TimeUnit.SECONDS)); System.out.println(b.get(3, TimeUnit.SECONDS)); } }}Expected output:
R-42:priceR-42:stockExplicit immutable context works without preview features. The owner joins both finite children.
Version contract
Virtual threads are stable from JDK 21 (JEP 444). ScopedValue was preview in JDK 21 and became final in JDK 25 (JEP 506). StructuredTaskScope is preview in JDK 21 and still preview in JDK 25 (JEP 505); the API shape changed, including the factory open and Joiner policy in JDK 25. Do not copy a Java 21 ShutdownOnFailure example into a Java 25 project. The following Java 25 snippets are documentation-reviewed, not compiled here.
Context and lifetime
A scoped value binds a reference for the dynamic extent of an operation and restores the prior binding afterward. Prefer immutable values; binding does not freeze a mutable object. Structured task scopes inherit captured scoped bindings when forked consistently. Arbitrary executor submissions do not automatically inherit those bindings. Ordinary parameters remain clearer for local data.
Ownership and failure
A Java 25 scope is opened and closed by its owner, forks subtasks, then joins once. The default join policy requires all tasks to succeed; failure cancels unfinished siblings via interruption. Scope closure waits for child termination, so uncooperative tasks can still delay it. A configured timeout can cancel a scope but does not forcibly kill a task. An executor with explicit cancellation illustrates the ownership idea but does not implement the same automatic fail-fast policy.
Cancel a sibling after an observed failure
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { CountDownLatch started = new CountDownLatch(1), gate = new CountDownLatch(1), done = new CountDownLatch(1); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Integer> sibling = executor.submit(() -> { started.countDown(); try { gate.await(3, TimeUnit.SECONDS); return 5; } finally { done.countDown(); } }); try { if (!started.await(3, TimeUnit.SECONDS)) throw new AssertionError("start deadline"); Future<Integer> failed = executor.submit(() -> { throw new IllegalArgumentException("bad input"); }); try { failed.get(3, TimeUnit.SECONDS); } catch (ExecutionException e) { System.out.println(e.getCause().getClass().getSimpleName()); sibling.cancel(true); } if (!done.await(3, TimeUnit.SECONDS)) throw new AssertionError("cleanup deadline"); System.out.println(sibling.isCancelled()); } finally { gate.countDown(); sibling.cancel(true); } } }}Expected output:
IllegalArgumentExceptiontrueThis is manual cancellation after observing the chosen future. It is not a general fail-fast task scope.
Collect a result only when both tasks succeed
import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.*;public class Main {
public static void main(String[] args) throws Exception { try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { Future<Integer> price = executor.submit(() -> 120); Future<Integer> fee = executor.submit(() -> 15); try { System.out.println(Math.addExact(price.get(3, TimeUnit.SECONDS), fee.get(3, TimeUnit.SECONDS))); } finally { price.cancel(true); fee.cancel(true); } } }}Expected output:
135Only publish the total after successful results. The finally block requests cancellation of unfinished tasks.
ScopedValue: bounded request context
Source-reviewed only; requires JDK 25. Not part of local passing cases.
public class Main { private static final ScopedValue<String> REQUEST = ScopedValue.newInstance(); static void report() { System.out.println(REQUEST.get()); } public static void main(String[] args) { ScopedValue.where(REQUEST, "R-17").run(Main::report); System.out.println(REQUEST.isBound()); }}Commands: javac --release 25 Main.java && java Main
Expected (not observed):
R-17falseStructuredTaskScope: Java 25 fifth preview
Source-reviewed only; requires JDK 25. Not part of local passing cases.
import java.util.concurrent.StructuredTaskScope;import java.time.Duration;public class Main { public static void main(String[] args) throws InterruptedException { try (var scope = StructuredTaskScope.open( StructuredTaskScope.Joiner.<Integer>awaitAllSuccessfulOrThrow(), config -> config.withTimeout(Duration.ofSeconds(3)))) { var subtotal = scope.fork(() -> 90); var shipping = scope.fork(() -> 10); scope.join(); System.out.println(subtotal.get() + shipping.get()); } }}Commands: javac --release 25 --enable-preview Main.java && java --enable-preview Main
Expected (not observed):
100Scoped context inherited by a structured child
Source-reviewed only; requires JDK 25. Not part of local passing cases.
import java.util.concurrent.StructuredTaskScope;public class Main { private static final ScopedValue<String> REQUEST = ScopedValue.newInstance(); public static void main(String[] args) throws Exception { String result = ScopedValue.where(REQUEST, "R-8").call(() -> { try (var scope = StructuredTaskScope.open()) { var child = scope.fork(() -> REQUEST.get() + ":ready"); scope.join(); return child.get(); } }); System.out.println(result); System.out.println(REQUEST.isBound()); }}Commands: javac --release 25 --enable-preview Main.java && java --enable-preview Main
Expected (not observed):
R-8:readyfalseCommon mistakes
Do not label StructuredTaskScope stable on JDK 25. Do not mix preview APIs across releases. Do not use a mutable object as a shared scoped value without appropriate synchronization. Do not assume closing a scope forcibly terminates an uncooperative child.
Practice
Use a record containing a request ID, submit two independent finite tasks returning that ID with suffixes A and B, and collect both using bounded gets. Explain what would change with Java 25 StructuredTaskScope.
Expected output:
Q-9-AQ-9-BCompare your answer with the manual practice criteria.
Official reading: JDK 25 changes · ScopedValue · StructuredTaskScope. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Versioned structured concurrency — knowledge check
Original virtual-thread and versioned concurrency questions.
What is the status of ScopedValue in Java 25?
How does a JDK 25 StructuredTaskScope start?
What does the default JDK 25 scope policy require?
What does a scoped binding protect?
What flags enable Java 25 preview features?