Video in progress
What is structured concurrency, and what problem is StructuredTaskScope trying to solve?
Structured concurrency is the idea that parallel subtasks can't "escape" the lexical block of their parent task: when the block ends, every child has finished or been cancelled. In Java 21, StructuredTaskScope shipped as a preview API, and it keeps changing in later versions.
📖 Answer
Typical code with an ExecutorService:
Future<User> user = pool.submit(() -> userService.find(id));
Future<List<Order>> orders = pool.submit(() -> orderService.list(id));
return new Profile(user.get(), orders.get());
The problems:
- if
user.get()fails, theorderstask keeps running, and nobody cancels it; - if the parent thread is interrupted, the children don't know about it;
- in a thread dump the children sit on pool threads, and you can't see who called them.
With the preview API in Java 21 (compile with --enable-preview):
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Subtask<User> user = scope.fork(() -> userService.find(id));
Subtask<List<Order>> orders = scope.fork(() -> orderService.list(id));
scope.join().throwIfFailed(); // if one fails, the other is cancelled
return new Profile(user.get(), orders.get());
}
The guarantees: when you leave the try block, all subtasks have finished; the first error cancels the rest; if the parent is interrupted, the children stop too. Each fork() starts a virtual thread by default. A JSON thread dump (jcmd <pid> Thread.dump_to_file -format=json) shows the parent-child hierarchy.
One catch: the API changed several times across the JDK 21-24 previews. In JDK 25 it moved to a new shape based on StructuredTaskScope.open() and Joiner, and it's still a preview. So in prod code I don't use it yet, or I hide it behind a thin wrapper. The idea itself can also be applied by hand with CompletableFuture: explicitly cancel the others on error and set an overall timeout.
Sign up to mark studied questions and save your progress.