java如何关闭钩子(ShutdownHook)
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<Thread, Thread> identityHashMap = (IdentityHashMap<Thread, Thread>) hooks.get(cls);
Iterator<Thread> iterator = identityHashMap.keySet().iterator();
while (iterator.hasNext()) {
Thread next = iterator.next();
if ("dahai1".equals(next.getName())) {
iterator.remove();
}
}
}
关于springboot dubbo停服,可以参考
https://blog.csdn.net/j3T9Z7H/article/details/102512557
https://blog.csdn.net/wins22237/article/details/72758644
https://www.jianshu.com/p/69b704279066
https://blog.csdn.net/qq_33220089/article/details/105708331
https://www.jianshu.com/p/555def4ac9b3
面朝大海```春暖花开