How to force terminate all workers in ThreadPoolExecutor immediately How to force terminate all workers in ThreadPoolExecutor immediately multithreading multithreading

How to force terminate all workers in ThreadPoolExecutor immediately


You cannot safely kill threads immediately. You tasks should instead honour interrupts and stop when interrupted. If you use ThreadPoolExecutor.shutdownNow(), all the running tasks will be interrupted.

The only alternative is to the threads in a separate process is issue a signal to kill the process.


Old question but I think you can extend ThreadPoolExecutor to capture running Thread reference in beforeExecute().When shutdownNow() would be called you can stop() all running Threads.Although I would strongly encourage relying on isInterrupted() in your tasks.

Sample code ->

public class KillableThreadPoolExecutor extends ThreadPoolExecutor {    private final Map<Runnable, Thread> executingThreads;    public KillableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, String threadNamePrefix) {        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new YoungMemorySafeLinkedBlockingQueue<Runnable>(), ThreadFactories.create(threadNamePrefix));        executingThreads = new HashMap<>(maximumPoolSize);    }    @Override    protected synchronized void beforeExecute(Thread t, Runnable r) {        super.beforeExecute(t, r);        executingThreads.put(r, t);    }    @Override    protected synchronized void afterExecute(Runnable r, Throwable t) {        super.afterExecute(r, t);        if(executingThreads.containsKey(r)) {            executingThreads.remove(r);        }    }    @Override    public synchronized List<Runnable> shutdownNow() {        List<Runnable> runnables = super.shutdownNow();        for(Thread t : executingThreads.values()) {            t.stop();        }        return runnables;    }}


The shutdown() will only make the ThreadPoolExecutor to reject all new submited tasks, and remove from the queue (if the ThreadPool is an unbounded queue executor) the pending tasks.The shutdownNow() will do exactly the same, and also will call to the interrupt() method of the Thread. So, in your run() method, you should handle it properly:

try {   Thread.sleep(1000);} catch (InterruptedException ie) {   // Handle the exception, and close resources.}