CompletableFuture Since Java 9: orTimeout or completeOnTimeout When a Deadline Fires?
0 reputation · 30 Mar 2025, 05:28 UTC
Deadline completion in CompletableFuture pipelines
Since Java 9, CompletableFuture includes two built-in deadline methods: orTimeout, which completes the future exceptionally with a TimeoutException, and completeOnTimeout, which completes it normally with a fallback value. Both only change the future's completion state.
The design tension is that neither method interrupts the task already submitted to the executor. When a deadline fires, dependent stages settle, but the underlying work keeps running — on ForkJoinPool.commonPool() for supplyAsync without an explicit executor, or on whatever custom ExecutorService was passed in.
Assuming a current LTS baseline such as JDK 17, the open decision is which strategy fits a pipeline whose callers expect graceful degradation:
- Should a deadline surface as a
TimeoutExceptionso retry and metrics logic can react, or is a silent default acceptable when downstream code cannot distinguish a fallback from a real result? - With no handle on the running task, what is the intended way to stop or signal abandoned work after
orTimeoutfires — or is it simply left to finish? - Do these completion semantics hold identically when a custom executor replaces the common pool?