1、简介
通过调用 Runtime.getRuntime().addShutdownHook() 可以注册一个虚拟机关闭钩子。
虚拟机在两种事件发生时会关闭:
第一种:程序正常退出,当应用的最后一个非守护线程结束时或者System.exit()方法被调用时(应用程序发生错误导致虚拟机停止也属于程序正常退出)。
第二种:用户主动中断程序。
2、实践案例
import java.util.ArrayList;
import java.util.List;
public class TestJVMHook {
public static void main(String[] args) {
Thread thread = new Thread(()->{
System.out.println("JVM意外终止");
System.out.println("开始关闭相关服务。。。");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("相关服务关闭成功。。。");
});
Runtime.getRuntime().addShutdownHook(thread);
List<Data> list = new ArrayList<>();
while (true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
list.add(new Data());
System.out.println(list.size());
}
}
static class Data{
byte[] bytes = new byte[1024 * 10];
}
}