addShutdownHook
Java程序中可以通过添加关闭钩子,实现在程序退出时关闭资源、平滑退出的功能。
同理关闭钩子是removeShutdownHook
使用Runtime.addShutdownHook(Thread hook)方法,可以注册一个JVM关闭的钩子,这个钩子可以在以下几种场景被调用
程序正常退出(比如main方法执行完毕)
使用System.exit()
终端使用Ctrl+C触发的中断
系统关闭
使用Kill -15 pid命令干掉进程
使用示例
public static void main(String[] args) {
Thread thread = new Thread(() -> System.out.println("Do something1 in Shutdown Hook"), "dahai1");
Runtime.getRuntime().addShutdownHook(thread);
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Do something2 in Shutdown Hook2"), "dahai2"));
System.out.println("hello world");
Runtime.getRuntime().removeShutdownHook(thread);
}
匿名函数如何移除
像dubbo等第三方依赖,默认在静态代码块中添加了shutdown hook,还是匿名函数
这个时候removeShutdownHook就无法使用了
反射移除
倘若指定了线程的名称,那么可以通过反射来移除
public static void main(String[] args) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Do something1 in Shutdown Hook1"), "dahai1"));
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Do something2 in Shutdown Hook2"), "dahai2"));
System.out.println("hello world");
Class> cls = Class.forName("java.lang.ApplicationShutdownHooks");
Field hooks = cls.getDeclaredField("hooks");
hooks.setAccessible(true);
IdentityHashMap identityHashMap = (IdentityHashMap) hooks.get(cls);
Iterator iterator = identityHashMap.keySet().iterator();
while (iterator.hasNext()) {
Thread next = iterator.next();
if ("dahai1".equals(next.getName())) {
iterator.remove();
}
}
}