Java / Java 21 Virtual Threads Interview questions
Explain the internal working of StructuredTaskScope's shutdown behavior?
Policies like ShutdownOnFailure and ShutdownOnSuccess watch the subtasks forked within a scope for a triggering condition - the first failure, or the first success, respectively.
Once that condition fires, the scope calls shutdown() internally, which interrupts every remaining forked virtual thread that hasn't finished yet. This is cooperative cancellation: a subtask must itself be interruption-aware (checking Thread.interrupted() or using interruptible blocking calls) to actually stop promptly rather than ignoring the interrupt.
The blocked scope.join() call in the parent then returns, after which methods like throwIfFailed() surface the captured exception (wrapped appropriately) to the caller. Finally, the implicit close() from try-with-resources verifies that no subtask thread is still running past the scope boundary - if one were, close() would wait for or forcibly account for it, upholding the guarantee that nothing outlives the scope.
More Related questions...