Runtime.getRuntime().addShutdownHook(shutdownHook);java
用途app
1應用程序正常退出,在退出時執行特定的業務邏輯,或者關閉資源等操做。jvm
2虛擬機非正常退出,好比用戶按下ctrl+c、OutofMemory宕機、操做系統關閉等。在退出時執行必要的挽救措施。spa
示例:操作系統
package com.ebways.mq.test.hook; /** * JVM鉤子 * Created by gmq on 2016/10/13 0013. */ public class JVMHook { public static void main(String[] args) { start(); // ==============================1: start========================== // 一、應用程序正常退出,在退出時執行特定的業務邏輯,或者關閉資源等操做。 // System.err.println("The Application is doing something"); // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // ==============================1: end========================== // ==============================2: start========================== // 2、虛擬機非正常退出,好比用戶按下ctrl+c、OutofMemory宕機、操做系統關閉等。在退出時執行必要的挽救措施。 System.err.println("The Application is doing something"); byte[] bytes = new byte[500 * 1024 * 1024]; throwException(); System.err.println("The Application continues to do something"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // ==============================2: end========================== } private static void throwException() { throw new OutOfMemoryError("ASDF"); } public static void start() { System.err.println("The JVM is started"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { // do something System.err.println("The JVM Hook is execute!"); } catch (Exception e) { e.printStackTrace(); } } }); } }
控制檯信息:線程
一、的狀況code
The JVM is started The Application is doing something The JVM Hook is execute! Process finished with exit code 0
最後一條是三秒後JVM關閉時候輸出的。對象
2:的狀況blog
The JVM is started The Application is doing something Exception in thread "main" java.lang.OutOfMemoryError: ASDF at com.ebways.mq.test.hook.JVMHook.throwException(JVMHook.java:41) at com.ebways.mq.test.hook.JVMHook.main(JVMHook.java:28) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) The JVM Hook is execute!
在OutOfMemoryError的時候能夠作一些補救措施。內存
建議:同一個JVM最好只使用一個關閉鉤子,而不是每一個服務都使用一個不一樣的關閉鉤子,使用多個關閉鉤子可能會出現當前這個鉤子所要依賴的服務可能已經被另一個關閉鉤子關閉了。爲了不這種狀況,建議關閉操做在單個線程中串行執行,從而避免了再關閉操做之間出現競態條件或者死鎖等問題。