如何在Java中实现优雅终止? [英] How do I implement graceful termination in Java?

查看:392
本文介绍了如何在Java中实现优雅终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说我让我的应用程序在Linux终端上运行,我按下键盘上的CTRL + C来终止它将终止Java程序的过程。



<是否有任何方法可以在我的Java应用程序中捕获此请求,以便我可以正常关闭它并释放所有资源/写入日志。如果它对响应产生影响,我会运行几个不同的线程。



我知道你有一个addShutDownHook,但是如Java文档中所写,它不是在某些情况下调用,比如linux中CTRL + C的kill信号......还有其他方法吗?

  Runtime.getRuntime()。addShutdownHook(new Thread()
{
public void run()
{
// TODO:在这里实现正常关闭。
}
});


解决方案

我认为免责声明只适用于 kill -9 ,这样你就不会依赖被调用的关闭钩子来维持你的数据的一致性。



因此,如果允许进程通过操作系统对该信号进行操作,则会调用关闭挂钩,如果您知道操作系统的工作方式,则可能非常明显,但可能并非所有Java开发人员都这样。



实际上在 javadoc



另外值得注意的是,可以注册多个关闭挂钩VM,所以你的可能不是关机钩子,只是其中一个。


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.
    }
});

解决方案

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.

这篇关于如何在Java中实现优雅终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆