CompletableFuture timeout vs cancel: which exception wins?
0 reputation · 02 Nov 2024, 19:36 UTC
CompletableFuture timeout vs cancel: which exception wins?
When a CompletableFuture is configured with completeOnTimeout and is later cancelled via cancel(true), the future completes exceptionally with a CancellationException. The timeout mechanism does not override this exception even if the timeout period elapses after the cancellation. This behaviour may surprise developers who expect a timeout to be the final failure signal.
The goal is to determine whether the timeout should supersede a prior cancellation, or whether the original cancellation should be preserved. The current implementation preserves the cancellation cause, but the design decision is not documented as a hard rule. Understanding this interaction is critical for building reliable fallback logic in asynchronous pipelines.
- Should a timeout that fires after a
CompletableFuturehas already been cancelled replace theCancellationExceptionwith aTimeoutException? - What is the official policy for exception precedence between
cancelandcompleteOnTimeoutin the Java API? - How can a developer design a fallback mechanism that reliably distinguishes a cancellation from a timeout when both are possible?