我们在阅读源码的时候,偶尔碰到下面这段代码:
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
从输出结果可以清除的看到程序的退出流程。