Scala CancellationException
A cancelled JVM future reports CancellationException when its result is requested.
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 Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonCollect 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
object Lesson {
def main(args: Array[String]): Unit = {
val job = new CompletableFuture[String]()
job.cancel(false)
try {
println(job.get())
} catch {
case problem: CancellationException =>
println("Print job cancelled")
}
}
}
Print job cancelled
The cancellation is visible before any result is collected. The dashboard can label the job accordingly.
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.
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.
What to watch for
Check whether cancellation succeeded before assuming an already running job has stopped.