Shutting Down an ExecutorService
In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new work to do.
In some cases this is very helpful, such as when an app needs to process tasks that appear on an irregular basis or the task quantity is not known at compile time.
On the other hand, an app could reach its end but not be stopped because a waiting ExecutorService will cause the JVM to keep running.
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.shutdown();The shutdownNow() method tries to destroy the ExecutorService immediately, but it doesn't guarantee that all the running threads will be stopped at the same time:
List<Runnable> notExecutedTasks = executorService.shutDownNow();This method returns a list of tasks that are waiting to be processed. It is up to the developer to decide what to do with these tasks.
One good way to shut down the ExecutorService (which is also recommended by Oracle) is to use both of these methods combined with the awaitTermination() method:
executorService.shutdown();
try {
if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}With this approach, the ExecutorService will first stop taking new tasks and then wait up to a specified period of time for all tasks to be completed. If that time expires, the execution is stopped immediately.
本文来源:https://www.baeldung.com/java-executor-service-tutorial
评论已关闭