• java 关闭钩子函数的应用


    Runtime.getRuntime().addShutdownHook(shutdownHook);

    说明:这个方法的意思就是在jvm中增加一个关闭的钩子,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。

    用途

    1应用程序正常退出,在退出时执行特定的业务逻辑,或者关闭资源等操作。

    2虚拟机非正常退出,比如用户按下ctrl+c、OutofMemory宕机、操作系统关闭等。在退出时执行必要的挽救措施。

    我的案例场景:后台服务代码实现的优雅停机,依赖于当服务宕机时,执行指定的destroy()方法,而不能直接关闭进程,后台有个任务线程要继续执行一段时间,所以在应用停止之前要调用指定的destroy()方法,去实现服务优雅停机,而java 提供的关闭钩子函数正好符合这一应用场景。

    public static void start(){
    	System.out.println("The JVM is started");
    	Runtime.getRuntime().addShutdownHook(new Thread(){
    	public void run(){
    	try{
    	    System.out.println("The JVM Hook is execute");
                RPCProvider.destroy();
                RPCStart.destroy();
            }catch (Exception e) {
    	    e.printStackTrace();
    	}
         }
       });
    }
    
    public static void main(String[] args) {
        start();
        System.out.println("The Application is doing something");
        try {
             Thread.sleep(3000);
        } catch (InterruptedException e) {
             e.printStackTrace();
        }
    }
    

    输出结果:

    The JVM is started
    The Application is doing something
    The JVM Hook is execute

     最后一条是三秒后JVM关闭时候输出

    参考:https://www.cnblogs.com/langtianya/p/4300282.html

  • 相关阅读:
    201141 live the lie until the lie becomes your life
    my php & mysql FAQ
    suger日料财务
    python 应用thrift thrift的监控fb303
    cherryPy学习
    my linux FAQ
    Javascript无阻塞加载方法
    设计模式学习笔记之组合模式模式
    【转】cookie
    C# 多线程
  • 原文地址:https://www.cnblogs.com/cowboys/p/8384738.html
Copyright © 2020-2023  润新知