钩子作用:
在线上Java程序中经常遇到进程程挂掉,一些状态没有正确的保存下来,这时候就需要在JVM关掉的时候执行一些清理现场的代码。Java中得ShutdownHook提供了比较好的方案。
JDK在1.3之后提供了Java Runtime.addShutdownHook(Thread hook)方法,可以注册一个JVM关闭的钩子,这个钩子可以在以下几种场景被调用:
触发条件:
- 程序正常退出
- 使用System.exit()
- 终端使用Ctrl+C触发的中断
- 系统关闭
- 使用Kill pid命令干掉进程
警告:在使用kill -9 pid是不会JVM注册的钩子不会被调用。
使用
方法:
Runtime.getRuntime().addShutdownHook(new CleanWorkThread());
示例:
package com.demo.rpc.hook;import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;public class TestShutdownHook {//简单模拟干活的static Timer timer = new Timer("job-timer");//计数干活次数static AtomicInteger count = new AtomicInteger(0);/*** hook线程*/static class CleanWorkThread extends Thread{@Overridepublic void run() {System.out.println("clean some work.");timer.cancel();try {Thread.sleep(2 * 1000);//sleep 2s} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) throws InterruptedException {//将hook线程添加到运行时环境中去Runtime.getRuntime().addShutdownHook(new CleanWorkThread());System.out.println("main class start ..... ");//简单模拟timer.schedule(new TimerTask() {@Overridepublic void run() {count.getAndIncrement();System.out.println("doing job " + count);if (count.get() == 10) { //干了10次退出System.exit(0);}}}, 0, 2 * 1000);}
}
转载文章:https://www.cnblogs.com/nexiyi/p/java_add_ShutdownHook.html