gpt4 book ai didi

java - 集合未在 java shutdown hook 中迭代

转载 作者:行者123 更新时间:2023-11-30 07:54:09 25 4
gpt4 key购买 nike

我已经在这个荒谬的问题上苦苦挣扎了几个小时,所以现在我正在寻求帮助。

1 liner:我的关闭钩子(Hook)显然在完成其职责之前就终止了。

我正在运行的代码如下所示:

class Test {

static {
Runtime.getRuntime().addShutdownHook(new Thread(Test::shutdown));
}

// more methods
private static void shutdown() {
Collection<Foo> coll = some.instance.ofHashMap.values();
System.out.println("collSize=" + coll.size());
for (Foo o : coll) {
System.out.println("Calling bar on foo");
o.bar();
}
System.out.println("End of hook");
}
}

但是输出是:

collSize=1

如果我使用 -server 选项运行 jvm,我可能会很幸运,并且会打印“Calling bar on foo”,但它仍然不会打印“End of hook”。

不幸的是,我无法创建一个简短的可执行示例来显示该问题。我有一个,但它显示一切正常,并且集合按预期迭代。上面的代码是我正在处理的一个更大的程序的摘录,但是我的关闭是钩子(Hook)除了上面的操作之外什么也没做(获取一个非空集合并迭代)。

对可能发生的事情有什么想法吗?我完全迷失在这里......

注释: - 代码是针对 Java 8u45 编写、编译和运行的 - 我用Ctrl+C杀死程序,结果,JVM存在,代码为130

最佳答案

来自the docs (强调我的)你只被 promise “尽最大努力”关闭 Hook :

Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible. They should also not rely blindly upon services that may have registered their own shutdown hooks and therefore may themselves in the process of shutting down. Attempts to use other thread-based services such as the AWT event-dispatch thread, for example, may lead to deadlocks.

Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.

所以,基本上,如果还有其他地方可以做,就在那里做。如果您必须在关闭 Hook 中执行此操作,请 Action 要快。

关于java - 集合未在 java shutdown hook 中迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32911602/

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