Java / Java 21 Virtual Threads Interview questions
Explain the execution flow of a structured concurrency task with subtasks failing?
Consider forking two subtasks under StructuredTaskScope.ShutdownOnFailure, where the first one throws an exception partway through.
- Both subtasks are forked as virtual threads and begin running concurrently.
- The first subtask throws an exception; the scope's failure policy captures it immediately.
- The policy triggers
shutdown(), which interrupts the still-running sibling subtask. - The sibling, if written to be interruption-aware, stops promptly instead of continuing to completion.
- The parent's blocked
scope.join()call returns. - Calling
scope.throwIfFailed()rethrows the captured exception (wrapped) to the caller. - The try-with-resources
close()confirms no subtask thread remains running past the scope.
The net effect is deterministic: a failure in one branch propagates cleanly to the caller and cancels its sibling, instead of leaving an orphaned background virtual thread running to no purpose after the parent has already moved on or reported an error.
More Related questions...