如何在 Java 中实现优雅终止?
举例来说,我的应用程序在 Linux 终端中运行,我按键盘上的“CTRL+C”来终止进程,它将终止 Java 程序。
有什么方法可以在我的 Java 应用程序中捕获此“请求”,以便我可以正常关闭它并释放所有资源/写入日志。如果它对响应产生影响,我会运行几个不同的线程。
我知道你有一个 addShutDownHook,但正如 Java 文档中所写,在某些情况下不会调用它,例如 Linux 中“CTRL+C”的终止信号......还有其他方法吗?
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run ()
{
// TODO: implement graceful shutdown here.
}
});
Say for instance I have my application running in a Linux terminal and I press "CTRL+C" on my keyboard to kill the process it will terminate the Java program.
Is there any way to catch this "request" in my Java application so I can shut it down gracefully and release all resources/write logs. I have several different threads running if it makes a difference to the response.
I know you have have an addShutDownHook, but as written in the Java documentation, it isn't called under certain circumstances, like the kill signal from "CTRL+C" in linux...are there any other ways?
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run ()
{
// TODO: implement graceful shutdown here.
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为免责声明仅适用于
kill -9
,因此您不必依赖调用的关闭挂钩来维护数据的一致性。因此,如果操作系统允许进程对信号进行操作,则会调用关闭挂钩,如果您了解操作系统的工作原理,那么这一点是非常明显的,但可能不是所有 Java 开发人员都知道。
它实际上在 javadoc。
另外值得记住的是,虚拟机中可以注册多个关闭挂钩,因此您的关闭挂钩可能不是关闭挂钩,而只是其中之一。
I think the disclaimer is only there for
kill -9
, so that you don't rely on the shutdown hook being invoked to maintain say the consistency of your data.So if the process is allowed to act on the signal by the OS, the shutdown hook is invoked, which is pretty obvious if you know how an OS works, but maybe not to all Java developers.
It is actually explained in great detail in the javadoc.
Also worth bearing in mind is that there can be multiple shutdown hooks registered in a VM, so yours might not be THE shutdown hook, just one of several.
这对我有用,在 Linux 上捕获 SIGINT/Ctrl-C:
This works for me, capturing SIGINT/Ctrl-C on Linux: