Java : CancellationException with Examples

CancellationException (Java SE 20 & JDK 20) API Examples.
You will find code examples on most CancellationException methods.


Summary

Exception indicating that the result of a value-producing task, such as a FutureTask, cannot be retrieved because the task was cancelled.

Class diagram

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- get start --");
    final var ret = future.get();

    System.out.println("-- get end --");
    System.out.println("ret = " + ret);
}

// Result
// ↓
//task start
//-- get start --
//task end
//-- get end --
//ret = abcd
try (final var executorService = Executors.newScheduledThreadPool(2)) {
    final var future = executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(3);

            return "abcd";
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
            return null;
        } finally {
            System.out.println("task end");
        }
    });

    executorService.schedule(() -> {
        System.out.println("future.cancel");
        future.cancel(true);
    }, 2, TimeUnit.SECONDS);

    try {
        System.out.println("-- get start --");
        final var ret = future.get();

        System.out.println("-- get end --");
        System.out.println("ret = " + ret);
    } catch (CancellationException e) {
        System.out.println("CancellationException!");
    }
}

// Result
// ↓
//task start
//-- get start --
//future.cancel
//Interrupted!
//CancellationException!
//task end

Constructors

CancellationException ()

Constructs a CancellationException with no detail message.

final var e = new CancellationException();
System.out.println(e); // java.util.concurrent.CancellationException

CancellationException (String message)

Constructs a CancellationException with the specified detail message.

final var e = new CancellationException("abcd");
System.out.println(e); // java.util.concurrent.CancellationException: abcd
System.out.println(e.getMessage()); // abcd

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page