zoukankan      html  css  js  c++  java
  • java的关闭钩子(Shutdown Hook)

    Runtime.getRuntime().addShutdownHook(shutdownHook);

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

    用途

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

     

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

     
    示例:

    public class JVMHook {

     public static void start(){
      System.out.println("The JVM is started");
      Runtime.getRuntime().addShutdownHook(new Thread(){
       public void run(){
        try{
         //do something
         System.out.println("The JVM Hook is execute");
        }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关闭时候输出的。

    针对用途第二点给的例子:
    package com.java.seven;
    public class JVMHook {
     public static void start(){
      System.out.println("The JVM is started");
      Runtime.getRuntime().addShutdownHook(new Thread(){
       public void run(){
        try{
         //do something
         System.out.println("The JVM Hook is execute");
        }catch (Exception e) {
         e.printStackTrace();
        }
       }
      });
     }
     
     public static void main(String[] args) {
      start();
      
      System.out.println("The Application is doing something");
      
      byte[] b = new byte[500*1024*1024];
      
      System.out.println("The Application continues to do something");
      
      try {
       Thread.sleep(3000);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    }

    输出结果:

    The JVM is started
    The Application is doing something
    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     at com.java.seven.JVMHook.main(JVMHook.java:24)
    The JVM Hook is execute

    在OutOfMemoryError的时候可以做一些补救措施。

    建议:同一个JVM最好只使用一个关闭钩子,而不是每个服务都使用一个不同的关闭钩子,使用多个关闭钩子可能会出现当前这个钩子所要依赖的服务可能已经被另外一个关闭钩子关闭了。为了避免这种情况,建议关闭操作在单个线程中串行执行,从而避免了再关闭操作之间出现竞态条件或者死锁等问题。

     

  • 相关阅读:
    发送带有正文以及附件的邮件
    软件测试笔记
    java开发 中台
    postman测试带有json数据格式的字段
    maven详解之仓库
    Maven与nexus关系
    占位
    Vue项目碰到"‘webpack-dev-server’不是内部或外部命令,也不是可运行的程序或批处理文件"报错
    了解facade设计模式
    postman使用
  • 原文地址:https://www.cnblogs.com/langtianya/p/4300282.html
Copyright © 2011-2022 走看看