What is Structured Concurrency, and what problem does it solve?
Structured Concurrency, finalized under JEP 505, guarantees that no child task can ever outlive the scope that created it. It solves several concrete problems that plague unstructured concurrent code. Thread leaks are prevented because closing the scope automatically cancels every child task still running inside it, whereas in unstructured code one failed task can leave its siblings running as orphans indefinitely. Exception propagation is simplified because a single child task's failure automatically cancels its siblings and propagates the failure up to the parent, instead of requiring manual bookkeeping to notice and react to it. Observability also improves, because a thread dump now shows a clear parent-child tree of tasks rather than an opaque flat list. The finalized API is used as StructuredTaskScope.open(joiner), where the Joiner argument selects the coordination policy: Joiner.allSuccessfulOrThrow() cancels every remaining task the moment any one of them fails, which fits a fan-out where every result is required, while Joiner.anySuccessfulResultOrThrow() cancels everything else the moment any one task succeeds, which fits patterns like hedged requests where you only need the fastest response. Earlier preview versions of this API exposed the same ideas through subclasses named ShutdownOnFailure and ShutdownOnSuccess; encountering that older shape in a codebase is a sign it predates the finalized API.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response