我們在閱讀源碼的時候,偶爾碰到下面這段代碼:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
logger.info("## stop the xxxx client");
clientTest.stop();
} catch (Throwable e) {
logger.warn("##something goes wrong when stopping xxxx:", e);
} finally {
logger.info("## xxx client is down.");
}
}
});
RunTime.getRunTime().addShutdownHook
的作用是往jvm中添加一個鈎子,當jvm關閉的時候(程式退出),jvm會調用所有注冊的鈎子函數。鈎子函數啟動一個獨立的線程,一般用來做資源的關閉和清理。
因為筆者以前是做c++開發的。是以在了解到java的這個特性的時候,當時第一個想法就是,這特麼不就是c++的析構函數嗎。在上面的代碼示例中,我們就是在鈎子函數裡調用用戶端的stop方法進行資源清理。
再來看一個例子:
public class RuntimeDemo {
public static void main(String[] args) throws Exception {
Runtime.getRuntime().addShutdownHook(new ProcessHook());
System.out.println("program is running");
Thread.sleep(2000);
System.out.println("program is closing");
}
static class ProcessHook extends Thread {
@Override
public void run() {
System.out.println("bye,byte");
}
}
}
輸出,
program is running
program is closing
bye,byte
Process finished with exit code 0
從輸出結果可以清除的看到程式的退出流程。