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-resourcesblock.
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
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:
| |
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:
| |
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():
| |
Why throwIfFailed() Is Essential
If fetchBreed() throws a RuntimeException while fetchName() is sleeping for 5 seconds:
ShutdownOnFailureimmediately interruptsfetchName()so you don't wait 5 seconds for a doomed request.- Calling
scope.throwIfFailed()afterscope.join()propagates the cause of the failure. (If you forget to callthrowIfFailed()and callbreed.get()directly on a failed subtask, it throws anIllegalStateException).
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:
| |
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):
| |
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:
- Java Virtual Threads Explained: Architecture, Creation & Performance
- The Hidden Cost of Java Virtual Threads: Deep Stacks, GC Pressure & Cache Locality
- How to Create Your Own Custom
StructuredTaskScopein Java - Java Scoped Values Tutorial: Faster, Safer Alternative to
ThreadLocal - Using
ExecutorService,Future&invokeAllwith Java Virtual Threads - Pitfalls to Avoid When Switching to Virtual Threads
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.
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: