如何给应用程序注入钩子程序

Runtime.getRuntime().addShutdownH
1、用来监测程序退出和出现异常死掉的情况
2、可以在程序退出和出现异常死掉时释放资源或给出通知
3、钩子程序只能检测到钩子程序之后程序的信息,一般放在程序前面

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_000);
                System.out.println("I am working...");
            } catch (Throwable e) {
                e.printStackTrace();
            }
            
            i++;
            if(i > 20) {
                throw new RuntimeException("error");
            }
        }
    }
    
    private static void notifyAndRelease() {
        System.out.println("notify to the admin.");
        
        try {
            Thread.sleep(1_000);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        
        System.out.println("Will release resource(socket,file,connection)");
        
        try {
            Thread.sleep(1_000);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        
        System.out.println("Release and notify done.");
    }
}

 

posted @ 2019-12-19 17:13  龙宇在天  阅读(583)  评论(0编辑  收藏  举报
//右侧添加目录 //增加页面点击显示24字社会主义核心价值观