Java SE API

CompletableFuture.cancel()

Cancel the future without using interruption to control its computation.

Formal Syntax & Structure

java syntaxjava
boolean cancel(boolean mayInterruptIfRunning)

Parameters & Attributes

NameTypeDescription
mayInterruptIfRunningbooleanIgnored by CompletableFuture; does not interrupt the supplier

Working Example

Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {    static ThreadPoolExecutor pool(int workers, int capacity) {        return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS,            new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy());    }    static void stop(ExecutorService pool) throws InterruptedException {        pool.shutdown();        try {            if (!pool.awaitTermination(3, TimeUnit.SECONDS)) {                for (Runnable pending : pool.shutdownNow()) {                    if (pending instanceof Future<?> future) future.cancel(false);                }                if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running");            }        } catch (InterruptedException e) {            for (Runnable pending : pool.shutdownNow()) {                if (pending instanceof Future<?> future) future.cancel(false);            }            throw e;        }    }    public static void main(String[] args) throws Exception {        ThreadPoolExecutor workers = pool(1, 1);        CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1);        CompletableFuture<Boolean> workerResult = new CompletableFuture<>();        try {            CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> {                entered.countDown();                try {                    if (!release.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("deadline");                    workerResult.complete(Thread.currentThread().isInterrupted());                    return 9;                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                    workerResult.complete(true);                    throw new CompletionException(e);                }            }, workers);            if (!entered.await(3, TimeUnit.SECONDS)) throw new AssertionError("not started");            CompletableFuture<Integer> dependent = result.thenApply(n -> n + 1);            System.out.println(result.cancel(true));            System.out.println(dependent.isCompletedExceptionally());            release.countDown();            System.out.println(workerResult.get(3, TimeUnit.SECONDS));        } finally { release.countDown(); stop(workers); }    }}
Java Reference