Failure and cancellation
What you will learn
An asynchronous failure travels through dependent stages. Choose deliberately whether to observe, recover from, or propagate it. Cancellation marks a CompletableFuture as failed with a cancellation exception; it is not a request that automatically interrupts the computation.
- Recover an expected failure while preserving unexpected failures.
- Distinguish handle, exceptionally and whenComplete.
- Explain exception wrapping and verify cancellation separately from worker exit.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Use the included bounded pool and shutdown helpers where applicable. The fixture runner also enforces a process deadline.
Recover only a known failure
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static final class MissingPrice extends RuntimeException { private static final long serialVersionUID = 1L; } public static void main(String[] args) throws Exception { CompletableFuture<Integer> lookup = new CompletableFuture<>(); CompletableFuture<Integer> recovered = lookup.exceptionally(error -> { Throwable cause = error instanceof CompletionException ? error.getCause() : error; if (cause instanceof MissingPrice) return 50; throw new CompletionException(cause); }); lookup.completeExceptionally(new MissingPrice()); System.out.println(recovered.join()); System.out.println(lookup.isCompletedExceptionally()); }}Expected output:
50trueA documented missing-price condition gets a fictional default. Other failures remain exceptional. The original future is not changed by recovery.
Observe or recover
exceptionally runs on failure and returns a replacement of the same result type. handle runs after either outcome and can transform to a new result type; inspect the exception rather than the result because null can be a valid success. whenComplete runs on either outcome and normally passes it through. If the observer throws after success, the dependent stage fails; if the source already failed, the source failure takes precedence. Observers should be short, reliable and free of blocking I/O.
Exceptions at the boundary
join generally reports failed completion as an unchecked CompletionException and cancellation directly as CancellationException on the cancelled future. get reports failures as checked ExecutionException and can also throw InterruptedException; timed get adds TimeoutException. A dependent of a cancelled future may wrap the cancellation in CompletionException and need not itself report isCancelled. Unwrap only known wrapper types when deciding how to recover. Never turn arbitrary failures into apparently valid business data. Keep an audit of which failures are recoverable.
Cancellation is not worker interruption
CompletableFuture.cancel(true) has the same interruption behavior as cancel(false): it does not use interrupts to control the underlying operation. A running supplier may finish even if its future has been cancelled. For a task you own, use a cooperative stop token or separately track the submitted Future and request interruption, then verify termination. Cancelling an aggregate or dependent stage does not generally cancel its inputs. Propagate cancellation only where you own the work; do not cancel another caller’s shared lookup.
Observe a failure and produce a status
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<String> lookup = new CompletableFuture<>(); CompletableFuture<String> observed = lookup.whenComplete((value, error) -> System.out.println(error == null ? "success" : "observed failure")); CompletableFuture<String> status = observed.handle((value, error) -> error == null ? "found: " + value : "unavailable"); lookup.completeExceptionally(new IllegalStateException("catalog offline")); System.out.println(status.join()); System.out.println(observed.isCompletedExceptionally()); }}Expected output:
observed failureunavailabletrueThe observer does not recover the failure. handle converts the outcome into a presentation status, not a substitute catalog item.
Compare join and get failures
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<Integer> failed = CompletableFuture.failedFuture(new IllegalArgumentException("bad input")); try { failed.join(); } catch (CompletionException e) { System.out.println(e.getCause().getClass().getSimpleName()); } try { failed.get(1, TimeUnit.SECONDS); } catch (ExecutionException e) { System.out.println(e.getCause().getMessage()); } }}Expected output:
IllegalArgumentExceptionbad inputBoth boundaries expose the original reason through a wrapper. get is interruptible, while join has no checked interruption exception.
Verify cancellation does not stop a running supplier
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ThreadPoolExecutor workers = pool(1, 1); CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1); CompletableFuture<Boolean> workerResult = new CompletableFuture<>(); try { CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> { entered.countDown(); try { if (!release.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("deadline"); workerResult.complete(Thread.currentThread().isInterrupted()); return 9; } catch (InterruptedException e) { Thread.currentThread().interrupt(); workerResult.complete(true); throw new CompletionException(e); } }, workers); if (!entered.await(3, TimeUnit.SECONDS)) throw new AssertionError("not started"); CompletableFuture<Integer> dependent = result.thenApply(n -> n + 1); System.out.println(result.cancel(true)); System.out.println(dependent.isCompletedExceptionally()); release.countDown(); System.out.println(workerResult.get(3, TimeUnit.SECONDS)); } finally { release.countDown(); stop(workers); } }}Expected output:
truetruefalseThe supplier was already running before cancellation. It leaves its wait normally after release, and the owned executor is stopped in finally. The cancelled future cannot later adopt the returned value.
Common mistakes
Do not swallow arbitrary exceptions with a default, test success via value != null, or assume whenComplete recovers a failure. Do not treat isCancelled as proof that a task exited. Keep cancellation ownership explicit.
Practice
Create a failed string future with IllegalStateException. Use handle to convert failure into the status "offline" and normal completion into the original value. Print the status and whether the original future remains exceptional.
Expected output:
offlinetrueCompare your answer with the manual practice criteria.
Official reading: CompletableFuture · CompletionStage. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Failure and cancellation — knowledge check
Original asynchronous workflow questions. Java 21-compatible scope.
Which callback observes both outcomes without normally replacing the result?
How do you distinguish a successful null result from failure in handle?
What does join normally throw for a failed non-cancelled stage?
Does CompletableFuture.cancel(true) interrupt its supplier automatically?
What happens to the original failed stage after exceptionally recovers?