gpt4 book ai didi

java - ExecutorService shutdownNow 没有关闭 JVM

转载 作者:行者123 更新时间:2023-12-02 01:27:20 25 4
gpt4 key购买 nike

正在学习 Java 1.5 中引入的 ExecutorService

以下示例似乎违反了预期行为:

public static void main(String[] args) throws InterruptedException,
ExecutionException,TimeoutException {

Callable<String> task = () -> {
int counter = 0;
while(true) {
//infinite loop will never exit
if(counter == 7) {
break;
}
}
return "abc";
};

ExecutorService service = Executors.newSingleThreadExecutor();
try {
Future<String> future = service.submit(task);

System.out.println("result = " + future.get(10000,TimeUnit.MILLISECONDS));
}finally {
System.out.println("<<<< finally >>>>");
service.shutdownNow();
}



}

查看此方法的 java 文档:

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

This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.

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

所以理想情况下,我期望的是在指定的超时后我会得到一个超时异常,然后 ExecutorService 将强制关闭,但这并没有发生。

查看了 java 文档 - 它似乎表明不能保证它会关闭。

如果不能保证,那么应该避免它吗?

最佳答案

Looked at the java doc - and it does seem to indicate that there is no guarantee that it would shutdown.

正确。

If its not guaranteed then should it be avoided ?

没有。

您实际上应该做的是使用 ExecutorService以避免或绕过限制的方式;例如

  • 实现任何可能长时间运行且应该可终止的任务,以便它们正确处理中断。如果你这样做正确,那么你的ExecutorService将终止。

  • 不要依赖 ExecutorService实际上正在关闭。例如,您可以安排当应用程序需要关闭时,它执行以下操作:

    1. 它调用shutdownNow()
    2. 它调用awaitTermination(...)有适当的超时
    3. 如果 ExecutorService不终止然后它调用 System.exit(...)终止应用程序。
  • 配置您的ExecutorService创建工作线程作为守护线程;请参阅Turning an ExecutorService to daemon in Java

    守护线程不会阻止 JVM 退出。但请注意,您需要小心。如果所有非守护线程都已完成,JVM 将拔掉插头,而不中断 ExecutorService 执行的任何任务。当前正在运行。

关于java - ExecutorService shutdownNow 没有关闭 JVM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com