Java Concurrency Interview

CompletableFuture and async composition question 98 of 180 senior

Does cancelling a CompletableFuture stop the work?

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.

completablefuture cancellation

Quiz yourself on CompletableFuture and async composition Suggest a correction