Library contents

Kotlin CancellationException

A cancelled JVM future reports CancellationException when its result is requested.

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

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

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

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
Lesson.kt
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CancellationException

fun main() {
    val job = CompletableFuture<String>()
    job.cancel(false)
    try {
        println(job.get())
    } catch (problem: CancellationException) {
        println("Print job cancelled")
    }
}
Output
Print job cancelled

The cancellation is visible before any result is collected. The dashboard can label the job accordingly.

Advertisements

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

Collect a withdrawn badge job

A class withdraws its badge job before printing begins. Collect the result of the print job. A cancelled job should be removed from the collection queue.

GivenCancelled job
Worked resultCancelled

What to watch for

Check whether cancellation succeeded before assuming an already running job has stopped.

Documentation for CancellationException