Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
Explain the internal working of structured concurrency in Java 21?
Structured concurrency, previewed in Java 21 via StructuredTaskScope (JEP 453), applies the idea of structured programming to concurrent tasks: a group of subtasks forked within a scope must all complete, be cancelled, or fail together, before the scope itself completes, so concurrent work gets a single, well-defined exit point instead of leaking independent threads.
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Supplier<String> user = scope.fork(() -> fetchUser()); Supplier<String> order = scope.fork(() -> fetchOrder()); scope.join(); // wait for both, or fail-fast on first failure scope.throwIfFailed(); // propagate any failure render(user.get(), order.get()); } // scope's try-with-resources close() ensures all forked threads are done or cancelled
Internally, fork() starts each subtask on its own virtual thread and tracks it as a child of the scope. ShutdownOnFailure cancels the sibling subtasks as soon as one fails, propagating that cancellation via interruption, while ShutdownOnSuccess instead stops once the first subtask succeeds. The scope's close(), called automatically by try-with-resources, blocks until every forked subtask has finished or been cancelled, guaranteeing no orphaned thread can outlive the block that created it.
This solves a real problem with unstructured concurrency: with plain ExecutorService calls, a failure in one concurrently launched task doesn't automatically stop its siblings, and a caller can easily forget to wait for everything it started, leaving threads running with no clear owner.
More Related questions...