往往在程序运行时,一些运行异常造成服务停止,但是资源为来得及释放,或者无法通知,这样会不友好。通过JDK中的Runtime.getRuntime().addShutdownHook()方法进行资源释放或者发送消息通知

/**
 * @Author: MR LIS
 * @Description:
 * @Date: Create in 17:46 2018/4/20
 * @Modified By:
 */
public class ExitCapture {

    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("The application will be exit.");
            notifyAndRelease();
        }));

//        int i=0;
        while (true) {
            try {
                Thread.sleep(1_000L);
                System.out.println("I am working");
            } catch (Throwable throwable) {
            }
//            i++;
            //模拟演示循环20次后抛出异常,实际情况不需要
         /*   if(i>20)
                throw new RuntimeException("run error");*/
        }
    }


    private static void notifyAndRelease() {
        System.out.println("notify to admin");
        try {
            Thread.sleep(1_000L);
        } catch (Throwable throwable) {
        }
        System.out.println("release resourcesocketconnection and so on");

    }
}

执行结果如下

Runtime注入钩子程序

在linux上通过 kill 进程号 ,和模拟演示中20次一样的效果(程序注释掉的部分),但是如果使用强杀进程,该钩子程序就没有作用,强杀:kill -9 进程号。实际项目中程序抛出异常和 kill 进程号一样的效果

相关文章: