package test.liuwei;
import lombok.extern.slf4j.Slf4j;
/**
* @author liuwei
* @date 2019-10-08 11:55
* @desc JVM关闭和ShutdownHook
* 非守护线程的自然结束会导致JVM进程结束
* 操作系统可以kill进程,如kill命令和Ctrl+C命令等可以主动结束JVM进程
* 除此之外,JDK提供了一些API可以在代码中主动关闭JVM
*/
@Slf4j
public class CloseJVM {
private static final int FAIL = -666;
private static Runtime currentRuntime = Runtime.getRuntime();
public static void main(String[] args) {
addALotHooks();
exit();
}
/**
* 当前运行环境currentRuntime退出
* 退出时通知shutdown hooks,运行uninvoked finalizers,然后调用halt方法
* The virtual machine's shutdown sequence consists of two phases.
* In the first phase all registered {shutdown hooks},
* if any, are started in some unspecified order and allowed to run concurrently until they finish.
* In the second phase all uninvoked finalizers are run if {finalization-on-exit} has been enabled.
* Once this is done the virtual machine {halts}.
*/
private static void exit(){
System.exit(FAIL);
}
/**
* 当前运行环境currentRuntime退出
* 强制退出,不通知shutdown hooks,不运行uninvoked finalizers
* this method does not cause shutdown hooks to be started
* and does not run uninvoked finalizers if finalization-on-exit has been enabled.
* If the shutdown sequence has already been initiated
* then this method does not wait for any running shutdown hooks or finalizers to finish their work
*/
private static void halt(){
currentRuntime.halt(FAIL);
}
/**
* 为JVM注册一个关闭钩子
* 钩子线程用以对服务和整个程序进行日志记录、临时数据清理等收尾操作
*/
private static void addAHook(){
currentRuntime.addShutdownHook(new Thread(){
public void run(){
log.info("我要回家了,永别了!");
}
});
}
/**
* 为JVM注册一组关闭钩子
* 钩子执行时不会按照注册顺序
*/
private static void addALotHooks(){
for (int i = 0; i < 5 ; i++) {
int index = i;
currentRuntime.addShutdownHook(new Thread(){
public void run(){
log.info("我是钩子{},我要回家了,永别了!", index);
}
});
}
}
}