如何正确关闭java ExecutorService [英] How to properly shutdown java ExecutorService

查看:188
本文介绍了如何正确关闭java ExecutorService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的java ExecutorService ,它运行一些任务对象(实现 Callable )。

I have a simple java ExecutorService that runs some task objects (implements Callable).

ExecutorService exec = Executors.newSingleThreadExecutor();
List<CallableTask> tasks = new ArrayList<>();
// ... create some tasks
for (CallableTask task : tasks) {
 Future future = exec.submit(task);
 result = (String) future.get(timeout, TimeUnit.SECONDS);
 // TASKS load some classes and invoke their methods (they may create additional threads)
 // ... catch interruptions and timeouts
}
exec.shutdownNow();

完成所有任务(DONE或TIMEOUT-ed)后,我尝试关闭执行程序,但是它不会停止: exec.isTerminated()= FALSE。
我怀疑某些被计时的任务没有被正确终止。

After all tasks are finished (either DONE or TIMEOUT-ed), I try to shutdown the executor, but it wont stop: exec.isTerminated() = FALSE. I suspect that some tasks that are timeouted are not properly terminated.

是的,我知道遗嘱执行人的关闭并不能保证任何事情:

And yes, I know that executor's shutdown is not guaranteing anything:


除了最好之外没有任何保证 - 努力尝试停止
处理主动执行任务。例如,典型的
实现将通过{@link Thread#interrupt}取消,因此任何无法响应中断的
任务可能永远不会终止。

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via {@link Thread#interrupt}, so any task that fails to respond to interrupts may never terminate.

我的问题是,有没有办法确保这些(任务)线程终止?
我提出的最佳解决方案是在程序结束时调用 System.exit(),但这很简单。

My question is, is there a way to ensure those (task) threads will terminate? The best solution I came up with, is to call the System.exit() at the end of my program, but that is plain silly.

推荐答案

来自 ExecutorService

 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }

如果你的游泳池花了更多时间关机,你可以改变

If your pool is taking more time to shutdown, you can change

1f (!pool.awaitTermination(60, TimeUnit.SECONDS))

while (!pool.awaitTermination(60, TimeUnit.SECONDS))






关闭关闭的简短摘要方法



shutdown()


有序启动关闭,其中先前提交的任务被执行,但不会接受任何新任务。

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

shutdownNow()


尝试停止所有activel执行任务,停止等待任务的处理,并返回等待执行的任务列表。

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

awaitTermination(long timeout,TimeUnit unit)抛出InterruptedException


阻止所有任务完成执行在关闭请求之后,或发生超时,或当前线程被中断,以先发生者为准。

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

这篇关于如何正确关闭java ExecutorService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆