Java CancellationException
Reading a cancelled future throws CancellationException. Cancellation has its own result state that a progress screen can display.
A simple example
CancellationException
- Start with A pending task is cancelled
- Do this Ask for its result
- Result Cancellation reported
Syntax
job.get()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCollect a cancelled print job
A student cancels a print job before the printer starts. When the dashboard later requests the result, it should show the cancellation as a distinct outcome.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CancellationException;
class Main {
public static void main(String[] args) throws Exception {
var job = new CompletableFuture<String>();
job.cancel(false);
try {
System.out.println(job.get());
} catch (CancellationException cancelled) {
System.out.println("Print job cancelled");
}
}
}
Print job cancelled
Cancellation completes this future in the cancelled state. Reading the result reports that state immediately.
Show the state of a completed print job
A library patron presses Cancel after the print server has already finished. The dashboard checks whether cancellation actually changed the job before it updates the patron's status.
import java.util.concurrent.CompletableFuture;
class Main {
public static void main(String[] args) throws Exception {
var job = CompletableFuture.completedFuture("Printed");
System.out.println(job.cancel(false) ? "Cancelled" : job.get());
}
}
Printed
cancel returns false on a future that already finished normally.
Collect a finished poster
The print room records completion before the clerk calls for the result. Collect the result of the print job. A cancelled job should be removed from the collection queue.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
CompletableFuture.completedFuture("poster").get();
System.out.println("Print ready");
} catch (CancellationException problem) {
System.out.println("Cancelled");
}
}
}
Print ready
What to watch for
Cancelling a future and interrupting a running task are separate concerns. This job is cancelled before any work starts.