The Problems With Unstructured Concurrency in Java: Leaks, Lost Errors and Orphaned Tasks
Why fanning out with ExecutorService and Future goes wrong when a subtask fails: orphaned siblings that keep running, failures noticed late because of the order of get() calls, interrupts that never reach subtasks, and thread dumps without task relationships. A demo and a first look at the fix.
kvi5hnuCode Sprout team member8 min readOn this page
Virtual threads made it cheap to run every blocking call in its own thread. They didn't change how those threads relate to each other. With ExecutorService and Future, a request that starts two subtasks has no built-in connection to them: each subtask lives on its own, whatever happens to the request or to its siblings. That's called unstructured concurrency, and this article shows what goes wrong with it, using the trip-quote service.
A typical fan-out
A quote needs a flight and a hotel. The two lookups are independent, so the service runs them concurrently and combines the results:
Future<String> hotel = executor.submit(() -> findHotel());
Future<String> flight = executor.submit(() -> findFlight());
return new Quote(flight.get(), hotel.get());
When both succeed, this is fine: the quote takes as long as the slower call. The problems start when one fails, or when the request itself is abandoned. The logic says the quote succeeds only if both succeed, but nothing in the code expresses that. The two futures don't know about each other or about the request.
Seeing the problems
The program below uses one long-lived executor shared by all requests, the usual setup in a service. findFlight fails after 100 ms, and findHotel takes 500 ms.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
record Quote(String flight, String hotel) {}
static final long START = System.nanoTime();
static final AtomicInteger hotelSearchesFinished = new AtomicInteger();
static long ms() { return Math.round((System.nanoTime() - START) / 1e6 / 100.0) * 100; }
static String findFlight(boolean fail) throws InterruptedException {
Thread.sleep(100);
if (fail) throw new IllegalStateException("flight service unavailable");
return "LIS->PRG";
}
static String findHotel() throws InterruptedException {
Thread.sleep(500); // slow, and nobody told it to stop
hotelSearchesFinished.incrementAndGet();
return "Hotel Mala Strana";
}
// The usual service style: one long-lived executor shared by all requests
static final ExecutorService SHARED = Executors.newVirtualThreadPerTaskExecutor();
static Quote quote(boolean flightFails) throws Exception {
Future<String> hotel = SHARED.submit(Solution::findHotel); // forked first
Future<String> flight = SHARED.submit(() -> findFlight(flightFails));
return new Quote(flight.get(), hotel.get()); // waits in this order
}
static Quote quoteHotelFirst(boolean flightFails) throws Exception {
Future<String> hotel = SHARED.submit(Solution::findHotel);
Future<String> flight = SHARED.submit(() -> findFlight(flightFails));
String h = hotel.get(); // waits 500 ms for the hotel...
return new Quote(flight.get(), h); // ...before seeing the flight failure
}
public static void main(String[] args) throws Exception {
// 1. The flight fails at 100 ms; the caller hears about it then, but the hotel search keeps going
try {
quote(true);
} catch (ExecutionException e) {
System.out.println(ms() + " ms: request failed: " + e.getCause().getMessage()
+ "; hotel searches finished so far: " + hotelSearchesFinished.get());
}
Thread.sleep(500);
System.out.println(ms() + " ms: hotel searches finished: " + hotelSearchesFinished.get()
+ " (the orphaned search ran to the end for nothing)");
// 2. Waiting in the wrong order: the failure is only noticed after the slow sibling
long t = System.nanoTime();
try {
quoteHotelFirst(true);
} catch (ExecutionException e) {
System.out.println("hotel-first wait: failure noticed after about "
+ Math.round((System.nanoTime() - t) / 1e6 / 100.0) * 100 + " ms, though it happened at 100 ms");
}
// 3. Interrupting the request thread doesn't cancel its subtasks
int before = hotelSearchesFinished.get();
Thread request = Thread.ofVirtual().start(() -> {
try {
quote(false);
} catch (InterruptedException e) {
System.out.println("request thread interrupted: it gives up waiting");
} catch (Exception e) {
System.out.println("unexpected: " + e);
}
});
Thread.sleep(50);
request.interrupt(); // e.g. the client disconnected
request.join();
Thread.sleep(600);
System.out.println("hotel searches finished after the interrupt: " + (hotelSearchesFinished.get() - before)
+ " (the subtasks never heard about it)");
SHARED.close();
}
}
Output (times rounded to 100 ms):
100 ms: request failed: flight service unavailable; hotel searches finished so far: 0
600 ms: hotel searches finished: 1 (the orphaned search ran to the end for nothing)
hotel-first wait: failure noticed after about 500 ms, though it happened at 100 ms
request thread interrupted: it gives up waiting
hotel searches finished after the interrupt: 1 (the subtasks never heard about it)

Problem 1: orphaned subtasks
When findFlight failed, flight.get() threw and the request ended with an error at 100 ms. The hotel search didn't know. It ran for another 400 ms, held a virtual thread and probably a connection to a hotel API, and produced a result that nobody would ever read.
With one request this is a small waste. Under load it adds up: every failed request leaves its slow siblings running, and they compete with live requests for downstream capacity. In the worst case, a struggling dependency fails fast, and the orphaned calls to the other dependencies pile up behind it. The fix by hand is to cancel the other futures in every error path, which is easy to forget and easy to get wrong.
Closing the executor in a try-with-resources block (article 9) doesn't solve this. close() waits for the orphan instead of cancelling it, so the request would take the full 500 ms to report a failure it knew about at 100 ms.
Problem 2: failures noticed late
In the second run, the code waited for the hotel first. The flight had failed at 100 ms, but hotel.get() only returned at 500 ms, and only then did flight.get() reveal the failure. The order of get() calls decided how long the caller waited, not the order in which things actually happened.
You can work around this with ExecutorCompletionService or invokeAny-style code that reacts to whichever task finishes first (article 21), but then you're writing coordination logic for every fan-out.
Problem 3: cancellation doesn't propagate
In the third run, the request thread was interrupted after 50 ms, as a server might do when the client disconnects. The thread stopped waiting in get(), but its two subtasks had no idea. The hotel search finished anyway. Interrupting a thread interrupts that thread only. Tasks it submitted to an executor aren't its children in any sense the JDK knows about.
Problem 4: no visible relationships
A thread dump of this service shows the request thread blocked in Future.get and, somewhere else, a virtual thread sleeping in findHotel. Nothing connects them. With hundreds of concurrent requests, you can't tell which subtasks belong to which request, or which ones are orphans. The executor's container in a JSON thread dump (article 17) lists threads, not a tree.
The root cause
All four problems have the same cause: the code's structure says "these two calls are part of one operation", but the runtime sees independent tasks. Sequential code doesn't have this problem. A method call can't outlive the method that called it, and an exception travels up to the caller. Unstructured concurrency gives that up: a Future can outlive the method that created it, be passed anywhere, and fail without anyone noticing.
It's similar to the case against goto. Once control can jump anywhere, you can't understand a block of code by reading it from top to bottom. Once a task can outlive the code that started it, you can't reason about a method's effects just by reading the method.
The fix, in brief
Structured concurrency brings back the rule from sequential code: subtasks start and end inside the block that created them. Here is the same failing quote with StructuredTaskScope, using the Java 27 preview API (the final API in Java 28 is the same):
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class Teaser {
record Quote(String flight, String hotel) {}
static volatile boolean hotelFinished;
static String findFlight() throws InterruptedException {
Thread.sleep(100);
throw new IllegalStateException("flight service unavailable");
}
static String findHotel() throws InterruptedException {
Thread.sleep(500);
hotelFinished = true;
return "Hotel Mala Strana";
}
static Quote quote() throws InterruptedException, ExecutionException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> hotel = scope.fork(Teaser::findHotel);
Subtask<String> flight = scope.fork(Teaser::findFlight);
scope.join(); // throws as soon as one subtask fails
return new Quote(flight.get(), hotel.get());
} // no subtask outlives this block
}
public static void main(String[] args) throws InterruptedException {
long start = System.nanoTime();
try {
quote();
} catch (ExecutionException e) {
long ms = Math.round((System.nanoTime() - start) / 1e6 / 100.0) * 100;
System.out.println(ms + " ms: request failed: " + e.getCause().getMessage());
}
Thread.sleep(600);
System.out.println("hotel search finished anyway: " + hotelFinished);
}
}
Output:
100 ms: request failed: flight service unavailable
hotel search finished anyway: false
The failure is reported at 100 ms whatever the fork order, and the hotel search is cancelled instead of being orphaned. If the request thread were interrupted while waiting, join() would throw InterruptedException, and leaving the block would make close() cancel both subtasks. The next articles explain how this works.
What's current
ExecutorServiceandFutureare unchanged and remain the right tool for independent background work that isn't part of one operation.StructuredTaskScopewas a preview API from Java 21 to Java 27 (JEP 533 is the seventh preview) and becomes final in Java 28 (JEP 543). The listing above uses the Java 27 API: a failing subtask makesjoin()throwExecutionException. Java 25 and 26 used a different exception, covered in article 37.- Running a preview API needs
--enable-previewon Java 27 (withjavac --release 27 --enable-previewwhen compiling). From Java 28 no flag is needed.
Common questions
Doesn't invokeAll solve this?
Partly. invokeAll waits for all tasks and returns their futures, but it doesn't cancel the others when one fails, so a fast failure still waits for the slow tasks. invokeAny cancels the losers, but it only covers "first success wins". Neither gives a block that owns its subtasks.
Can't I just cancel the other futures in a catch block?
Yes, and careful code does that. But you have to do it in every error path, including interrupts and timeouts, in the right order, and then still wait for the cancelled tasks to actually stop. Structured concurrency does all of that in join() and close().
Is unstructured concurrency always wrong? No. Fire-and-forget work that really is independent of the request, such as sending an audit event or warming a cache, doesn't need to be tied to it. The problems appear when tasks are logically part of one operation but the code treats them as unrelated.
Do virtual threads make the leaks cheaper? They make each orphan cheaper in memory, but the orphan still does its work: it still calls the downstream service, holds a connection and uses CPU. Cheap threads can make leaks easier to miss.
Summary
- Unstructured concurrency means subtasks have no built-in relationship to the task that started them or to each other.
- When one subtask fails, its siblings keep running as orphans, wasting downstream capacity.
- The order of
get()calls can delay noticing a failure until a slow sibling finishes. - Interrupting the parent thread doesn't cancel its subtasks, and thread dumps don't show which subtasks belong to which request.
- Structured concurrency ties subtasks to a block: a failure cancels the siblings, and no subtask outlives the block.
Practice questions
A method submits three calls to a shared executor and calls get() on each in order. The second fails after 50 ms, the first takes 2 seconds. When does the method report the failure, and what happens to the third call?
Answer
After about 2 seconds, because it waits for the first future before it reaches the second. The third call keeps running to completion (or failure) on its own, since nothing cancels it. Its result is never read.
Why doesn't wrapping the fan-out in try (var executor = Executors.newVirtualThreadPerTaskExecutor()) fix orphaned subtasks?
Answer
close() waits for every submitted task to finish. It doesn't cancel them. A failure noticed at 100 ms would still wait for a 500 ms sibling before the block ends. It prevents leaks beyond the block, but not wasted work, and it makes the failure path slower.
A server interrupts a request thread when the client disconnects. The request thread was waiting on two futures. What happens to the two subtasks?
Answer
Nothing. The interrupt only affects the request thread, which stops waiting and sees InterruptedException. The subtasks run on other threads and aren't connected to it, so they keep running unless the code explicitly cancels their futures.
Previous: Building Virtual Threads From Scratch in Java With Continuations
Next: Structured Concurrency in Java: The Principles Behind StructuredTaskScope

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.