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