Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force terminate all workers in ThreadPoolExecutor immediately

I have a number of tasks inside a TheadPoolExecutor. I have a stop button on my interface that should terminate all the threads inside ThreadPoolExecutor immediately. I am looking for a way to do it. (without shutDown() or shutDownNow()).

Thanks

like image 824
deadlock Avatar asked Oct 10 '12 14:10

deadlock


People also ask

How do you terminate ThreadPoolExecutor?

cancel() Won't Stop Running Tasks You can call the cancel() function on the Future object to cancel the task before it has started running. If your task has already started running, then calling cancel() will have no effect and you must wait for the task to complete.

How do you kill ThreadPoolExecutor in Python?

You can cancel tasks in the ThreadPoolExecutor by calling the cancel() function on the Future object.

How do you kill an executor in Java?

The ExecutorService class has 2 methods just for this: shutdown() and shutdownNow(). After using the shutdown() method, you can call awaitTermination() to block until all of the started tasks have completed. You can even provide a timeout to prevent waiting forever.

How do I kill the thread in ExecutorService?

To properly shut down an ExecutorService, we have the shutdown() and shutdownNow() APIs. The shutdown() method doesn't cause immediate destruction of the ExecutorService. It will make the ExecutorService stop accepting new tasks and shut down after all running threads finish their current work: executorService.


1 Answers

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.

like image 57
Peter Lawrey Avatar answered Oct 20 '22 17:10

Peter Lawrey