JVM关闭和ShutdownHook

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);
                }
            });
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值