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

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.");
    }
}
原文地址:https://www.cnblogs.com/zheaven/p/12068913.html