shutdown() 后需要 ExecutorService.awaitTermination()

Need for ExecutorService.awaitTermination() after shutdown()

根据 Javadocs,shutdown() 将等待所有提交任务执行完毕。我有两个问题:

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)。