
Conditional Cancellation in Java 21: When Sibling Work Should Stop
Note This article uses Java 21 preview structured concurrency APIs (JEP 453). See Part 9 for migration changes in Java 25 preview APIs. Compile and run with --enable-preview . Originally published on engnotes.dev: Conditional Cancellation in Java 21 This is a shortened version with the same core code and takeaways. Timeouts are only one kind of failure. A lot of expensive failures happen when the outcome is already decided, but parts of the request are still doing work anyway. Payment failed. Risk check failed. Circuit breaker is already open. In those cases, letting sibling tasks continue is usually just wasted load. That is where conditional cancellation becomes useful. The Fail-Fast Version One practical Java 21 pattern is to turn a terminal business failure into an exception inside the subtask, so ShutdownOnFailure can cancel sibling work: public String circuitBreakerExample () throws Exception { if ( circuitBreakerFailures . get () > 3 ) { logger . warn ( "Circuit breaker is OPEN
Continue reading on Dev.to
Opens in a new tab
