📜  Java中的 JVM 关闭挂钩

📅  最后修改于: 2022-05-13 01:55:06.272000             🧑  作者: Mango

Java中的 JVM 关闭挂钩

Shutdown Hooks 是一种特殊的结构,它允许开发人员插入一段代码,以便在 JVM 关闭时执行。这在我们需要进行特殊清理操作以防虚拟机关闭时派上用场。
使用一般结构来处理这个问题,例如确保我们在应用程序退出之前调用特殊过程(调用 System.exit(0) )对于由于外部原因(例如终止请求)而关闭 VM 的情况将不起作用来自 O/S),或由于资源问题(内存不足)。正如我们很快将看到的,关闭钩子很容易解决这个问题,它允许我们提供任意代码块,JVM 关闭时将调用该代码块。
从表面上看,使用关闭钩子非常简单。我们所要做的只是编写一个扩展Java.lang.Thread 类的类,并在公共 void run() 方法中提供我们想要在 VM 关闭时执行的逻辑。然后我们通过调用 Runtime.getRuntime().addShutdownHook(Thread) 方法将此类的一个实例注册为 VM 的关闭挂钩。如果您需要删除之前注册的关闭挂钩,Runtime 类也提供了 removeShutdownHook(Thread) 方法。
示例 1(匿名内部类):

Java
public class ShutDownHook
{
  public static void main(String[] args)
  {
 
    Runtime.getRuntime().addShutdownHook(new Thread()
    {
      public void run()
      {
        System.out.println("Shutdown Hook is running !");
      }
    });
    System.out.println("Application Terminating ...");
  }
}


Java
class ThreadChild extends Thread {
     
    public void run() {
         
        System.out.println("In clean up code");
        System.out.println("In shutdown hook");
    }
}
 
class Demo {
     
    public static void main(String[] args) {
         
        Runtime current = Runtime.getRuntime();
        current.addShutdownHook(new ThreadChild());
 
        for(int i = 1; i <= 10; i++)
            System.out.println("2 X " + i + " = " + 2 * i);
    }
}


当我们运行上面的代码时,你会看到关闭钩子在 JVM 完成 main 方法的执行时被调用。
输出:

Application Terminating ...
Shutdown Hook is running !

示例 2

Java

class ThreadChild extends Thread {
     
    public void run() {
         
        System.out.println("In clean up code");
        System.out.println("In shutdown hook");
    }
}
 
class Demo {
     
    public static void main(String[] args) {
         
        Runtime current = Runtime.getRuntime();
        current.addShutdownHook(new ThreadChild());
 
        for(int i = 1; i <= 10; i++)
            System.out.println("2 X " + i + " = " + 2 * i);
    }
}

输出:

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
In clean up code
In shutdown hook