1:写在前面
jvm shutdown hook,即虚拟机关闭钩子,是允许在虚拟机退出前执行一些操作的机制,可以用于进行一些资源的清理等善后工作,对于包括但不限于以下的情况注册的虚拟机关闭钩子会被执行。
1:程序的正常退出
2:System.exit()
3:Ctrl+C
4:OutOfMemoryError
5:kill pid(注意非“-9”)
下面我们来测试下这些中的部分情况。
2:程序正常退出
2.1:测试代码
public class ShutdownHookTest {
public void registerShutdownHook() {
System.out.println("register shutdown hook begin...");
// 注册停止运行钩子
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("shut downhook run ...");
}));
System.out.println("register shutdown hook end...");
}
public static void main(String[] args) throws Exception {
// 先注册停止运行钩子
new ShutdownHookTest().registerShutdownHook();
// 模拟正常的应用程序运行
System.out.println("application running...");
Thread.sleep(3000);
System.out.println("application run over...");
}
}
2.2:运行
register shutdown hook begin...
register shutdown hook end...
application running...
application run over...
shut downhook run ...
3:OutOfMemoryError
3.1:测试代码
public class ShutdownHookOutOfMemoryTest {
public void registerOutOfMemoryShutdownHook() {
System.out.println("register out of memory shut down hook begin...");
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("out of memory shutdown hook run ...");
}));
System.out.println("register out of memory shut down hook end...");
}
public static void main(String[] args) throws Exception {
// 注册虚拟机关闭钩子
new ShutdownHookOutOfMemoryTest().registerOutOfMemoryShutdownHook();
// 因为配置-Xmx20M,所以这里会发生OutOfMemoryError
int FIFTY_M = 1024 * 1024 * 50;
byte[] b = new byte[FIFTY_M];
System.out.println("application running...");
Thread.sleep(3000);
}
}
3.2:运行
注意配置-Xmx20M
:
register out of memory shut down hook begin...
register out of memory shut down hook end...
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
out of memory shutdown hook run ...