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
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.
You can cancel tasks in the ThreadPoolExecutor by calling the cancel() function on the Future object.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With