CompletableFuture and async composition question 98 of 180 senior
Does cancelling a CompletableFuture stop the work?
- Yes, it interrupts the running thread
- Correct: No:
cancelcompletes the future exceptionally but the running task carries on, because there is no thread associated with the future - Only if you pass
true - It throws if the task has started
CompletableFuture.cancel(mayInterruptIfRunning) ignores its argument. A CompletableFuture is a
value holder with no link back to whoever is computing it, so all cancelling does is complete it with a
CancellationException and release the dependent stages. The supplyAsync task keeps running to
completion, holding its thread and its connection.
This is a real difference from FutureTask, where cancel(true) does interrupt the worker. If you
need genuine cancellation you have to arrange it yourself: keep the Future returned by the executor,
check a flag inside the task, or use StructuredTaskScope, which was designed to make cancellation
propagate.
Quiz yourself on CompletableFuture and async composition Suggest a correction