CancellationException

Learn the reasons that cause CancellationException to be thrown.

We'll cover the following

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

CancellationException is thrown to indicate that the output or result of a value producing task can’t be retrieved because it was cancelled. CancellationException is an unchecked exception and extends IllegalStateException, which in turn extends the RuntimeException. Some of the classes that throw CancellationException exception are:

  • FutureTask
  • CompletableFuture
  • ForkJoinTask

Example

The following program demonstrates a scenario where an instance of CancellationException is thrown by the program. We create a FutureTask that has the thread sleep for one second intervals for a total of one hour. The main thread submits the task to the executor service, waits for three seconds and then attempts to cancel the task.Next when the main thread attempts to retrieve the result of the task by invoking the get() method on the task object, CancellationException exception is thrown.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy