Java 如何捕获 System.exit 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/914666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to capture System.exit event?
提问by harshit
I have an application in java, in which i try to ensure that the if anybody exits codes System.exit() in the code , an listener should be called to do some stuff like logging message and releasing the resources ...
我在java中有一个应用程序,其中我尝试确保如果有人在代码中退出代码 System.exit() ,则应调用侦听器来执行某些操作,例如记录消息和释放资源...
How can i implement it, any suggestion/approach is welcome.
我该如何实施它,欢迎任何建议/方法。
采纳答案by coobird
The Runtime.addShutdownHook
method can be used to add a shutdown hook, which is basically a unstarted Thread
, which executes on shutdown of the Java Virtual Machine.
该Runtime.addShutdownHook
方法可用于添加关闭钩子,它基本上是一个 unstarted Thread
,它在 Java 虚拟机关闭时执行。
However, this is territory that should to be tread carefully, as it is being performed at a very sensitive time of the JVM's life cycle. From the API Specifications for the Runtime.addShutdownHook
method:
然而,这是应该小心谨慎的领域,因为它是在 JVM 生命周期的一个非常敏感的时间执行的。来自该Runtime.addShutdownHook
方法的 API 规范:
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.
关闭钩子在虚拟机生命周期的一个微妙时刻运行,因此应该进行防御性编码。特别是,它们应该被编写为线程安全的,并尽可能避免死锁。
In any event, be sure to read up a bit on how shutdown hooks work, as they probably should not be approached without some good preparation. Be sure to carefully read the API Specification for the Runtime.addShutdownHook
method.
无论如何,请务必阅读有关关闭挂钩如何工作的一些内容,因为如果没有做好充分的准备,可能不应该接触它们。请务必仔细阅读该Runtime.addShutdownHook
方法的 API 规范。
Here's are a couple articles I found from searching for information for this answer:
以下是我在搜索此答案的信息时发现的几篇文章:
Shutdown Hooks-- it shows a little example of how a shutdown hook is added for logging at shutdown.
Design of the Shutdown Hooks API-- addresses some design decisions of shutdown hooks in a question and answer style.
Shutdown Hooks——它展示了一个关于如何在关机时为日志记录添加关机钩子的小例子。
Shutdown Hooks API 的设计——以问答的方式解决了一些关闭钩子的设计决策。
回答by Silfverstrom
The function Runtime.addShutdownHook(Thread thehook)
allows you to register a hook into the Java Virtual Machine.
The hook works as an initialized but unstarted thread, which will be called by the JVM on exit. In case you register more than one hook, note that the order in which the hooks are called is undefined.
该函数Runtime.addShutdownHook(Thread thehook)
允许您将钩子注册到 Java 虚拟机中。
该钩子作为一个已初始化但未启动的线程工作,它将在退出时由 JVM 调用。如果您注册了多个钩子,请注意钩子的调用顺序是未定义的。