java的關閉鉤子(Shutdown Hook)

來源:互聯網
上載者:User

標籤:int   continue   程式   trace   href   ror   tar   started   ring   

https://www.cnblogs.com/langtianya/p/4300282.html#undefined

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的關閉鉤子(Shutdown Hook)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.