Search code examples
javaexecutorservice

ExecutorService - cancel pending tasks


There are multiple questions about waiting for an Java ExecutorService to finish (shutdown() + awaitTermination()) or alternatively cancel them all (shutdownNow()).

I'd like to go for an early exit without interrupting the tasks that have started already. You could also say I'd like to

  • stop allowing further submissions (shutdown())
  • cancel all tasks that are still pending
  • wait for the in-flight tasks to terminate (awaitTermination())

How do I efficiently implement the cancellation?


Solution

  • Slaw had the right idea. It got me where I am now, and the solution works nicely.

    First off, I switched from a generic Executor to a ThreadPoolExecutor. When instantiating it, I defined the queue to use - which allows me to watch progress, or clear it if need be.

    In a nutshell, my code looks like this:

        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(numThreads, numThreads, 10L, TimeUnit.MILLISECONDS, queue);
    
        // submit all the jobs here
    
        // wait until all jobs have processed
        executor.shutdown();
        boolean earlyExit = false; // this variable would have to be set by some event
        while (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
            if (earlyExit && !queue.isEmpty()) {
                queue.clear();
            }
        }