如何捕获System.exit事件? [英] How to capture System.exit event?
问题描述
我在java中有一个应用程序,我试图确保if ifbody在代码中退出代码System.exit(),应该调用一个监听器来做一些事情,如记录消息和释放资源......
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 ...
我如何实现它,欢迎任何建议/方法。
How can i implement it, any suggestion/approach is welcome.
推荐答案
Runtime.addShutdownHook
方法可以用来添加一个关闭钩子,它基本上是一个未启动的 Thread
,在关闭Java虚拟机时执行。
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.
然而,这是应谨慎行事的领域,因为它是在JVM的非常敏感的时间执行的。生命周期。来自 Runtime.addShutdownHook
方法的API规范:
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:
关闭挂钩运行于虚拟机生命周期
的微妙时间
,因此应该在防御上编码
。它们应该以
特别写成
线程安全,并尽可能避免死锁
。
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.
无论如何,请务必仔细阅读关闭钩子如何工作,因为如果没有一些好的准备,可能不应该接近它们。请务必仔细阅读 Runtime.addShutdownHook
方法的API规范。
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.
以下是我发现的几篇文章从搜索此答案的信息:
Here's are a couple articles I found from searching for information for this answer:
-
Shutdown Hooks - 它显示了一个关于如何在关机时添加关闭挂钩的示例。
Shutdown Hooks -- it shows a little example of how a shutdown hook is added for logging at shutdown.
设计Shutdown Hooks API - 以问答形式解决关闭挂钩的一些设计决策。
Design of the Shutdown Hooks API -- addresses some design decisions of shutdown hooks in a question and answer style.
这篇关于如何捕获System.exit事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!