Intercepting java machine shutdown call?

强颜欢笑 提交于 2019-12-04 03:40:56

问题


Is there any way to get notified of JVM shutting down or System.exit call before the actual shutdown? I want this, so my application will be able to make a clean exit. I realize that such thing is unlikely to exist, but still, maybe there is something like this?


回答1:


Have a look at Runtime.addShutdownHook

From the API docs:

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

Using Runtime.addShutdownHook you can run code in those cases.




回答2:


There's Runtime.getRuntime().addShutdownHook() method that you might want to explore.



来源:https://stackoverflow.com/questions/4564276/intercepting-java-machine-shutdown-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!