Java 程序经常也会遇到进程挂掉的情况,一些状态没有正确的保存下来,这时候就需要在 JVM 关掉的时候执行一些清理现场的代码。JAVA 中的 ShutdownHook 提供了比较好的方案。
JDK 提供了 Java.Runtime.addShutdownHook(Thread hook) 方法,可以注册一个 JVM 关闭的钩子,这个钩子可以在一下几种场景中被调用:
下面是 JDK1.7 中关于钩子的定义:
- public void addShutdownHook(Thread hook)
- 参数:
- hook - An initialized but unstarted Thread object
- 抛出:
- IllegalArgumentException - If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run
- IllegalStateException - If the virtual machine is already in the process of shutting down
- SecurityException - If a security manager is present and it denies RuntimePermission("shutdownHooks")
- 从以下版本开始:
- 1.3
- 另请参见:
- removeShutdownHook(java.lang.Thread), halt(int), exit(int)
来测试第一种,程序正常退出的情况:
- import java.util.concurrent.TimeUnit;
- public class HookTest
- {
- public void start()
- {
- Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
- @Override
- public void run()
- {
- System.out.println("Execute Hook.....");
- }
- }));
- }
- public static void main(String[] args)
- {
- new HookTest().start();
- System.out.println("The Application is doing something");
- try
- {
- TimeUnit.MILLISECONDS.sleep(5000);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- }
- }
运行结果:
The Application is doing something
Execute Hook.....
来源: