[英]Java shutdown hook not running
I have a product service in Java.我有一个 Java 产品服务。 In our code I am creating shut down hook, but when I stop service it is not calling shut down hook consistently.在我们的代码中,我正在创建关闭挂钩,但是当我停止服务时,它并没有始终如一地调用关闭挂钩。 Out of 5 stop calls it has called shutdown hook only once.在 5 次停止调用中,它只调用了一次关闭挂钩。
Runnable shutdownHandler = new Runnable() {
@Override
public void run() {
s_log.info("Shutting down thread..");
}
};
Runtime.getRuntime().addShutdownHook(
new Thread(shutdownHandler, "shutdownthread"));
Can anybody please tell me what could be the reason behind this not getting called consistently?任何人都可以告诉我这背后没有一直被调用的原因是什么?
Check the following code:检查以下代码:
Runnable shutdownHandler = new Runnable() {
@Override
public void run() {
System.out.println("Shutting down thread..");
}
};
Runtime.getRuntime().addShutdownHook(
new Thread(shutdownHandler, "shutdownthread"));
and if it gives you expected output, you need to check the documentation of your logging framework.如果它给了你预期的输出,你需要检查你的日志框架的文档。
I am also finding that my framework (Jooby) and Java shutdown hooks work fine on my Mac on IntelliJ which sends a kill SIGINT (-2) however on Ubuntu Server 20.04 LTS they don't run.我还发现我的框架 (Jooby) 和 Java 关闭挂钩在 IntelliJ 上的 Mac 上运行良好,它发送了一个 kill SIGINT (-2) 但是在 Ubuntu Server 20.04 LTS 上它们不运行。
As my Java app is a webapp I came up with a simple workaround:由于我的 Java 应用程序是一个 web 应用程序,我想出了一个简单的解决方法:
Setup a controller to listen to some url that isn't easily guessable eg设置一个控制器来监听一些不容易猜到的 url,例如
/exit/fuuzfhuaBFDUWYEGLI823y82941u9y47t3u45
Have the controller simply do the following:让控制器简单地执行以下操作:
System.exit(0)
Do a curl or wget from a script to the URL and the shutdown hooks all fire as JVM comes down.从脚本到 URL 执行 curl 或 wget 操作,当 JVM 关闭时,关闭钩子会全部触发。
I suspect for some reason on Linux there is a bug and no matter what interrupt that I use besides SIGKILL they all effectively behave like SIGKILL and the JVM comes down hard/abruptly.我怀疑出于某种原因在 Linux 上存在一个错误,无论我使用什么中断,除了 SIGKILL 之外,它们都有效地表现得像 SIGKILL,并且 JVM 会硬/突然地停机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.