Future Cancel Interrupts Running Task

cancel(true) sends an interrupt to a running Future's worker thread and marks the task cancelled, after which get() throws CancellationException forever.

JavaResilience

Code

snippet
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ReportJob {

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> job = pool.submit(() -> {
            try {
                for (int round = 1; round <= 100; round++) {
                    Thread.sleep(50); // each pass takes time, the whole job is far from done
                }
                return "done";
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // restore the interrupt flag before exiting
                return "interrupted";
            }
        });

        Thread.sleep(120); // let it run roughly two passes first
        System.out.println("cancel(true) accepted: " + job.cancel(true));
        System.out.println("isCancelled: " + job.isCancelled() + ", isDone: " + job.isDone());
        try {
            job.get(); // a cancelled task never produces a result
        } catch (CancellationException e) {
            System.out.println("get() on cancelled future -> CancellationException");
        }
        pool.shutdownNow();
    }
}

Inside the snippet

Future Cancel Interrupts Running Task reduces to the class ReportJob.

Iteration happens inside for (int round = 1; round <= 100; round++) — everything outside it runs once.

Putting it to use

The demo output is labeled (cancel(true) accepted:, isCancelled:), so every printed line maps back to its originating operation.

Core lines

ExecutorService pool = Executors.newSingleThreadExecutor();
Thread.currentThread().interrupt(); // restore the interrupt flag before exiting
return "interrupted";
Thread.sleep(50); // each pass takes time, the whole job is far from done
}

Interactive Tools for This Topic

FAQ

What does Future Cancel Interrupts Running Task print when run?
The script runs standalone; its 2 labeled outputs include `cancel(true) accepted:`, `isCancelled:`.