引言
最近在研究比特流的源码,看到Runtime.getRuntime().addShutdownHook(Thread hook)时,发现全然不知所云,速查之,特总结如下。
何时调用
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, orThe 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.
Thus, a shutdown hook is a initialized and unstarted thread that gets executed when a JVM shutdown occurs.
示例代码
|
|
代码输出:
Shutdown hook registered
Before calling exit
Inside Shutdown hook
Shutdown hook thread sleeping for 2 seconds
Shutdown hook thread waking up
Shutdown hook thread terminating
|
|
代码输出:
Calling System.exit()
Running finalize()
Running Shutdown Hook
总结:总是在虚拟机关闭之前调用
使用场景
- your program had created many temporary files in filesystem you want to delete it;
- you need to send a distress signal to another process/machine before terminating;
- execute any clean-up actions, logging or after-error actions on unexpected behaviours.
声明
本文70%为翻译组合,30%为原创