Java / Java 21 Coding Standards Interview Questions
Why is structured concurrency recommended over raw thread management in Java 21?
Structured concurrency (a preview feature in Java 21 via StructuredTaskScope) treats a group of related subtasks as a single unit of work: if one subtask fails, the others are cancelled, and the parent does not proceed until every child has either completed or been cancelled.
sequenceDiagram
participant Parent
participant TaskA
participant TaskB
Parent->>TaskA: fork()
Parent->>TaskB: fork()
TaskA-->>Parent: result
TaskB-->>Parent: failure
Parent->>TaskA: cancel (scope closes on failure)
Parent->>Parent: join() rethrows failure
Raw thread management with manually created threads and shared futures makes this coordination the programmer's job: a failure in one thread does not automatically stop its siblings, so it is easy to leak a running thread that keeps working on a result nobody needs anymore, or to leave an exception silently swallowed in a future that was never checked.
Structured concurrency's core coding-standard benefit is that a subtask's lifetime can never outlive its enclosing scope; the try (var scope = ...) block guarantees every forked subtask is joined or cancelled before the block exits, which eliminates leaked threads as a category of bug rather than relying on the developer to remember cleanup in every code path.
More Related questions...