想必各位对于Runtime这个单词并不陌生,比如通常我们用的RuntimeException(运行时异常)。那么Runtime到底指的什么呢,单从字面意思理解“运行时”,当然此处并不会对于这个类做过多解释。所以我这里也就废话少说了!
Runtime中有getRuntime()方法,获得运行时对象。那么通过这个运行时对象,我们可以看到它有exec()、freeMemory()、totalMemory()、availableProcessors()、exit()等方法。
不过上述方法我们都不会讲解,直入主题。
addShutdownHook(Thread hook) {
从字面不难理解,就是添加一个线程钩子。通过这个方法,我们可以创建JVM的钩子,那么在JVM关闭时,我们就可以在这个钩子里做一些清理工作。
这个钩子可以在以下几种场景被调用:
- 1)程序正常退出
- 2)使用System.exit()
- 3)终端使用Ctrl+C触发的中断
- 4)系统关闭
- 5)使用Kill pid命令干掉进程
参数
hook -- 一个初始化但尚未启动的线程对象,注册到JVM钩子的运行代码。
异常
IllegalArgumentException -- 如果指定的钩已被注册,或如果它可以判定钩已经运行或已被运行
IllegalStateException -- 如果虚拟机已经是在关闭的过程中
SecurityException -- 如果存在安全管理器并且它拒绝的RuntimePermission(“shutdownHooks”)
当遇到 MySQL 驱动问题时,可按如下方式关闭
十二月 28, 2015 4:15:58 下午 org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
严重: The web application [/elasticsearch] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
十二月 28, 2015 4:15:58 下午 org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
严重: The web application [/elasticsearch] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
//安全删除注册的mysql驱动
Class.forName("com.mysql.jdbc.Driver", true, ClassUtils.getDefaultClassLoader());
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
logger.info("unregister mysql driver");
while (DriverManager.getDrivers().hasMoreElements())
DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
// AbandonedConnectionCleanupThread.shutdown();//5.1.25版本开始需要使用,否则在tomcat关闭时会有错误
} catch (Throwable e) {
e.printStackTrace();
}
}
});