如何知道当前是否正在关闭?
在 Tomcat 中,当服务器关闭时,它会尝试将其知道的类中的所有静态变量设置为 null。通过接触这些类,它们的静态初始化程序就会运行,这可能会导致我们的一些具有大量静态初始化程序的遗留类陷入无限循环。
有没有一种优雅的方法来检测当前是否正在进行关闭?然后,我们可以在静态初始化程序的顶部检查是否处于关闭模式,然后忽略初始化。
我们发现唯一可行的方法一点也不优雅:
try{
Thread hook = new Thread();
Runtime.getRuntime().addShutdownHook( hook ); // fires "java.lang.IllegalStateException: Shutdown in progress" if currently in shutdown
Runtime.getRuntime().removeShutdownHook( hook );
}catch(Throwable th){
throw new Error("Init in shutdown thread", th );
}
In Tomcat, when the server is being shut down, it tries to set all static variables in classes it knows of to null. By touching these classes, their static initializers are run, which can result in an endless loop for some of our legacy classes which have massive static initializers .
Is there an elegant way to detect whether a shutdown is currently in progress? We could then check at the top of the static initializers whether we are in shutdown mode and then ignore the initialization.
The only way we found which seems to work is anything but elegant:
try{
Thread hook = new Thread();
Runtime.getRuntime().addShutdownHook( hook ); // fires "java.lang.IllegalStateException: Shutdown in progress" if currently in shutdown
Runtime.getRuntime().removeShutdownHook( hook );
}catch(Throwable th){
throw new Error("Init in shutdown thread", th );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以看看Tomcat是否使用了一个新的线程来做关闭工作,如果是的话你可以遍历当前线程并寻找这个线程。
接下来,设置 ServletContextListener,以便它在 contextInitialized 和 contextDestroyed 中打开和关闭标志,您的类检查该标志。
You can look if Tomcat uses a new Thread to do shutdown work, if yes you could traverse current threads and look for this thread.
Next, setting up ServletContextListener, so that it turns flag on and off in contextInitialized and contextDestroyed, your classes check that flag.
您可以控制 webapp 配置吗?如果是这样,您可以通过在
/META-INF/context.xml
中设置来禁用清除静态引用,如 文档
否则,我同意在 ServletContextListener 中设置标志可能是你的最好的选择。
Do you have control over the webapp configuration? If so, you can disable clearing static references by setting,
in
/META-INF/context.xml
as stated in the documentationOtherwise, I agree that setting a flag in the ServletContextListener is probably your best option.