Contents

Structured Concurrency in Java: StructuredTaskScope, ShutdownOnFailure, ShutdownOnSuccess & Deadlines

Updated on 2026-10-21

Introduction: Why Structured Concurrency?

When you spawn concurrent tasks across multiple threads, handling partial failures, timeouts, and thread cancellation quickly gets messy. If task A fails while task B is still calling an external HTTP service, forgetting to cancel task B creates a thread leak (an orphan thread running in the background wasting resources).

Structured Concurrency solves this by applying the principles of structured programming to multithreading:

If a task splits into concurrent subtasks, they all return to the same place: the task's code block. The lifetime of a child virtual thread can never exceed the lexical scope of its parent try-with-resources block.

In this guide, we cover how to group and coordinate Java Virtual Threads using both ExecutorService and StructuredTaskScope, how Subtask handles results, how to use ShutdownOnFailure (InvokeAll pattern) and ShutdownOnSuccess (InvokeAny pattern), and how to enforce timeouts with joinUntil().


How Structured Concurrency Works

Thread YThread XStart thread XPerform workPerform workDone!Thread Y is finishedbecause its work andThreads X work is doneThread YThread X

When Parent Thread Y forks Child Thread X inside a structured scope, both execute concurrently. However, Thread Y cannot exit the try-with-resources block until Thread X has either completed or been cancelled. No fire-and-forget orphan threads can escape the block.


1. Basic Thread Grouping with AutoCloseable ExecutorService

In Java 21+, ExecutorService extends AutoCloseable. The simplest way to bind a group of virtual threads to a lexical scope is wrapping Executors.newVirtualThreadPerTaskExecutor() in a try-with-resources statement:

1
2
3
4
5
6
7
Runnable printTask = () -> System.out.println("Running on: " + Thread.currentThread());

try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(printTask);
    executor.submit(printTask);
    executor.submit(printTask);
} // Waits here until all 3 virtual threads finish before continuing!

Ordered Cancellation with Nested Executors

When a try-with-resources block exits, resources are closed in reverse declaration order. If you have producer virtual threads sending data to a consumer database virtual thread, declaring two executors ensures the producers shut down cleanly before the consumer closes:

1
2
3
4
5
try (ExecutorService consumer = Executors.newVirtualThreadPerTaskExecutor();
     ExecutorService producers = Executors.newVirtualThreadPerTaskExecutor()) {
    consumer.submit(() -> producers.awaitTermination(1L, TimeUnit.DAYS));
    producers.submit(() -> System.out.println("Producing data while consumer is active"));
} // 'producers' closes first, then 'consumer' closes

However, a plain ExecutorService does not automatically short-circuit and cancel sibling tasks when one task throws an exception. For that, we need StructuredTaskScope.


2. The “InvokeAll” Pattern: StructuredTaskScope.ShutdownOnFailure

StructuredTaskScope.ShutdownOnFailure implements the “all-or-nothing” (invokeAll) pattern: if any forked subtask fails with an exception, all other still-running subtasks in the scope are immediately cancelled (interrupt()ed).

Note that in modern Java (JDK 21+), scope.fork(...) returns a Subtask<T> (rather than Future<T> from early Java 19 incubator builds), and you retrieve the value with .get() after calling scope.join() and scope.throwIfFailed():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;

public class StructuredConcurrencyExamples {

    String getDogProfile() throws ExecutionException, InterruptedException {
        try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
            Subtask<String> name = scope.fork(this::fetchName);
            Subtask<String> breed = scope.fork(this::fetchBreed);

            // Wait for all subtasks to complete (or for any one to fail)
            scope.join();
            // Rethrow the underlying exception if any subtask failed
            scope.throwIfFailed();

            // Safe, non-blocking retrieval because join() & throwIfFailed() succeeded
            return "Name: " + name.get() + ", Breed: " + breed.get();
        }
    }

    String fetchName() { return "Max"; }
    String fetchBreed() { return "Golden Retriever"; }
}

Why throwIfFailed() Is Essential

If fetchBreed() throws a RuntimeException while fetchName() is sleeping for 5 seconds:

  1. ShutdownOnFailure immediately interrupts fetchName() so you don't wait 5 seconds for a doomed request.
  2. Calling scope.throwIfFailed() after scope.join() propagates the cause of the failure. (If you forget to call throwIfFailed() and call breed.get() directly on a failed subtask, it throws an IllegalStateException).

3. The “InvokeAny” Pattern: StructuredTaskScope.ShutdownOnSuccess

Unlike ShutdownOnFailure (which waits for every subtask), StructuredTaskScope.ShutdownOnSuccess<T> implements the race / fallback (invokeAny) pattern: it captures the result of the first subtask to succeed and immediately cancels all remaining subtasks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
String getFastestDogResponse() throws ExecutionException, InterruptedException {
    try (var scope = new StructuredTaskScope.ShutdownOnSuccess<String>()) {
        scope.fork(this::slowService);
        scope.fork(this::fastService);

        // Unblocks as soon as the first subtask succeeds!
        scope.join();

        // Returns "Golden Retriever" and cancels slowService()
        return "Winner: " + scope.result();
    }
}

String slowService() throws InterruptedException {
    Thread.sleep(5000);
    return "Max";
}

String fastService() {
    return "Golden Retriever";
}

4. Setting Timeouts & Deadlines with joinUntil(Instant)

In production microservices, you never want a fan-out call to hang indefinitely. Both ShutdownOnFailure and ShutdownOnSuccess provide joinUntil(Instant deadline):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.TimeoutException;

String fetchWithDeadline() throws ExecutionException, InterruptedException, TimeoutException {
    try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
        Subtask<String> serviceA = scope.fork(this::fetchName);
        Subtask<String> serviceB = scope.fork(this::fetchBreed);

        // Cancel all running subtasks and throw TimeoutException if not done within 2 seconds
        scope.joinUntil(Instant.now().plus(Duration.ofSeconds(2)))
             .throwIfFailed();

        return serviceA.get() + " - " + serviceB.get();
    }
}

If the deadline expires before the subtasks finish, joinUntil() automatically cancels all subtasks in the scope and throws a TimeoutException—guaranteeing zero leaked background threads.


5. Custom StructuredTaskScope Policies

Need a custom policy (such as quorum voting, collecting partial successes while ignoring failures, or rate-limited fan-out)? You can extend StructuredTaskScope<T> and override handleComplete(Subtask<? extends T> subtask). Read my dedicated tutorial: How to Create Your Own Custom StructuredTaskScope in Java.


Conclusion & Further Reading

Structured Concurrency transforms concurrent error handling, cancellation, and deadlines from fragile manual plumbing into a clean lexical scope.

Explore more guides on Virtual Threads and Concurrency:

🚀 In-House Team Workshop · 1 Day (Live In-Person On-Site)

Adopt Virtual Threads & Structured Concurrency Without Production Surprises

Virtual threads look simple on paper—until carrier thread pinning, unmounted stack heap pressure, or legacy ThreadLocals hit production. Bring me in for a tailored 1-day Java Virtual Threads, Structured Concurrency & Scoped Values Workshop built around your team's actual architecture and frameworks.

Stay Connected · Code, Benchmarks & Talks

Want More Deep-Dive JVM Benchmarks & Project Panama Research?

Follow my weekly engineering posts on LinkedIn, explore the full JMH benchmark suites and pure-Java Linux io_uring / FUSE projects on GitHub, or download my conference talk slides:

David Vlijmincx
David Vlijmincx

Senior Java Performance & Concurrency Engineer with 10+ years of production JVM experience. International speaker with 35+ talks at Devoxx, P99 CONF, JFokus, JavaZone, and Devnexus, creator of JUring (Linux io_uring for Java), and enterprise Java workshop trainer.