解析Runtime中shutdown hook的應用詳解。本站提示廣大學習愛好者:(解析Runtime中shutdown hook的應用詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是解析Runtime中shutdown hook的應用詳解正文
依據 Java API, 所謂 shutdown hook 就是曾經初始化但還沒有開端履行的線程對象。在Runtime 注冊後,假如 jvm 要停滯前,這些 shutdown hook 便開端履行。聲明:Runtime.addShutdownHook(Thread t)
舉例以下:
package john2;
/**
* test shutdown hook
* All rights released and correctness not guaranteed.
*/
public class ShutdownHook implements Runnable {
public ShutdownHook() {
// register a shutdown hook for this class.
// a shutdown hook is an initialzed but not started thread, which will get up and run
// when the JVM is about to exit. this is used for short clean up tasks.
Runtime.getRuntime().addShutdownHook(new Thread(this));
System.out.println(">>> shutdown hook registered");
}
// this method will be executed of course, since it's a Runnable.
// tasks should not be light and short, accessing database is alright though.
public void run() {
System.out.println("/n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits.");
this.cleanUp();
System.out.println(">>> Finished execution: " + ShutdownHook.class.getName() + ".run()");
}
// (-: a very simple task to execute
private void cleanUp() {
for(int i=0; i < 7; i++) {
System.out.println(i);
}
}
/**
* there're couple of cases that JVM will exit, according to the Java api doc.
* typically:
* 1. method called: System.exit(int)
* 2. ctrl-C pressed on the console.
* 3. the last non-daemon thread exits.
* 4. user logoff or system shutdown.
* @param args
*/
public static void main(String[] args) {
new ShutdownHook();
System.out.println(">>> Sleeping for 5 seconds, try ctrl-C now if you like.");
try {
Thread.sleep(5000); // (-: give u the time to try ctrl-C
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println(">>> Slept for 10 seconds and the main thread exited.");
}
}
或許有人會擔憂機能成績,shutdown hook會不會占用太多的VM的資本,謎底是shutdown hook不會占用VM太多的資本,由於shutdown hook 只是一個已初始化但還沒有啟動的線程。這意味著它只在法式封閉的時刻才會啟動,而不是在法式一開端運轉時就啟動。而在年夜多半的Java平台中,假如一個線程沒有啟動(即沒有挪用線程的start()函數)VM不會分派資本給線程。是以保護一群沒有啟動的線程不會給VM帶來太年夜的累贅.
最初還要留意以下兩點:
假如VM crash,那末不克不及包管封閉掛鉤(shutdown hooks)能運轉.試想一下假如Windows XP忽然藍屏了那末原來籌劃在關機之前的更新也就沒法停止了.
假如挪用Runtime.halt()辦法來停止法式的話,那末封閉掛鉤(shutdown hooks)也不會履行