Library contents

Java CancellationException

Reading a cancelled future throws CancellationException. Cancellation has its own result state that a progress screen can display.

A simple example

CancellationException

  1. Start with A pending task is cancelled
  2. Do this Ask for its result
  3. Result Cancellation reported
Cancellation is a distinct outcome, so the caller can handle it separately from success.

Syntax

Java syntax
job.get()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Collect 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.

ResultPrint job cancelled
Main.java
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");
        }
    }
}
Output
Print job cancelled

Cancellation completes this future in the cancelled state. Reading the result reports that state immediately.

Advertisements

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.

ResultPrinted
Main.java
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());
    }
}
Output
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.

GivenCompleted job
Worked resultPrint ready
Code and output in Java
Java source
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");
        }
    }
}
Output
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.

Documentation for CancellationException