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最好只使用一個關閉鈎子,而不是每個服務都使用一個不同的關閉鈎子,使用多個關閉鈎子可能會出現當前這個鈎子所要依賴的服務可能已經被另外一個關閉鈎子關閉了。為了避免這種情況,建議關閉操作在單個線程中串行執行,從而避免了再關閉操作之間出現競態條件或者死鎖等問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM