JVM支持在程序kill的时候根据kill 信号进行优雅关闭。
首先我们需要在Runtime.getRuntime().addShutdownHook(thread);中注册要执行的内容。
public class GracefulTest {
public static void main(String[] args) throws InterruptedException {
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("Fuck you!");
}));
for (; ; ) {
System.out.println(" Watching you ...");
Thread.sleep(500);
}
}
}
当我们强制关闭:
kill -9 49261
Watching you ...
Watching you ...
Watching you ...
Watching you ...
Process finished with exit code 137 (interrupted by signal 9: SIGKILL)
使用-15(优雅关闭)时:
kill -15 49400
Watching you ...
Watching you ...
Watching you ...
Watching you ...
Fuck you!
Process finished with exit code 143 (interrupted by signal 15: SIGTERM)
可以看到我们需要关闭的逻辑被执行了。

本文探讨了如何在Java程序中利用JVM的Shutdown Hook机制来实现当接收到不同信号(如SIGKILL和SIGTERM)时执行预定义的清理逻辑。通过实例展示了如何在程序被强制kill时确保关键操作的正确执行。
1118

被折叠的 条评论
为什么被折叠?



