shutdown() 后需要 ExecutorService.awaitTermination()
Need for ExecutorService.awaitTermination() after shutdown()
根据 Javadocs,shutdown() 将等待所有提交任务执行完毕。我有两个问题:
- 提交的任务是什么意思?任务是否必须通过 ExecutorService.submit() 方法专门提交,或者它还包括通过 ExecutorService.execute() 方法提交的任务?
- 我添加了一个调用 ExecutorService.shutdown() 的关闭钩子。根据文档,它应该等待所有提交任务被执行。但直到我在 shutdown() 调用之后添加 awaitTermination() 调用时才会发生。为什么它不在没有 awaitTermination() 调用的情况下执行所有任务?
What does submitted task mean? Do the tasks have to be submitted specifically by ExecutorService.submit() method or it included tasks submitted by ExecutorService.execute() method also?
A 'submitted' 这个意义上的任务是传递给 ExecutorService 的任何 Runnable 或 Callable。虽然 javadoc 的措辞有点混乱,但它没有区分 execute()
和 submit()
.
I have added a shutdown hook which calls ExecutorService.shutdown(). As per the docs, it should wait for all submit tasks to be executed. But it doesn't until I add a awaitTermination() call after the shutdown() call. Why doesn't it execute all tasks without awaitTermination() call?
shutdown() 操作与 ExecutorService API 上的几乎所有方法一样是非阻塞(异步)操作。 javadoc 仅声明调用 shutdown()
将 启动 关闭序列。
这里的关键是ExecutorService会尝试等待所有任务完成,但是如果shutdown()
是你的main方法终止前的最后一行代码, System.exit()
将在您的 main 方法结束后调用,这将终止 JVM 并覆盖 ExecutorService 等待 运行 任务完成的尝试。我认为 ExecutorService.shutdown()
总是延迟 System.exit()
是不可取的,并且更喜欢选择加入方法而不是阻塞调用(即 awaitTermination
)。
根据 Javadocs,shutdown() 将等待所有提交任务执行完毕。我有两个问题:
- 提交的任务是什么意思?任务是否必须通过 ExecutorService.submit() 方法专门提交,或者它还包括通过 ExecutorService.execute() 方法提交的任务?
- 我添加了一个调用 ExecutorService.shutdown() 的关闭钩子。根据文档,它应该等待所有提交任务被执行。但直到我在 shutdown() 调用之后添加 awaitTermination() 调用时才会发生。为什么它不在没有 awaitTermination() 调用的情况下执行所有任务?
What does submitted task mean? Do the tasks have to be submitted specifically by ExecutorService.submit() method or it included tasks submitted by ExecutorService.execute() method also?
A 'submitted' 这个意义上的任务是传递给 ExecutorService 的任何 Runnable 或 Callable。虽然 javadoc 的措辞有点混乱,但它没有区分 execute()
和 submit()
.
I have added a shutdown hook which calls ExecutorService.shutdown(). As per the docs, it should wait for all submit tasks to be executed. But it doesn't until I add a awaitTermination() call after the shutdown() call. Why doesn't it execute all tasks without awaitTermination() call?
shutdown() 操作与 ExecutorService API 上的几乎所有方法一样是非阻塞(异步)操作。 javadoc 仅声明调用 shutdown()
将 启动 关闭序列。
这里的关键是ExecutorService会尝试等待所有任务完成,但是如果shutdown()
是你的main方法终止前的最后一行代码, System.exit()
将在您的 main 方法结束后调用,这将终止 JVM 并覆盖 ExecutorService 等待 运行 任务完成的尝试。我认为 ExecutorService.shutdown()
总是延迟 System.exit()
是不可取的,并且更喜欢选择加入方法而不是阻塞调用(即 awaitTermination
)。