zoukankan      html  css  js  c++  java
  • 如何给应用程序注入钩子程序

    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.");
        }
    }
  • 相关阅读:
    015.Python函数名的使用以及函数变量的操作
    014.Python函数
    013.Python的文件操作
    012.Python的字典和集合的相关函数
    git入门
    Visual Studio 常见的快捷键
    SVN使用
    C++ 一些特性
    C++ 引用、构造函数、移动语义
    WPF的AutoCompleteBox控件
  • 原文地址:https://www.cnblogs.com/zheaven/p/12068913.html
Copyright © 2011-2022 走看看