您的位置:首页 > 运维架构 > Tomcat

Spring整合ElasticJob 关闭Tomcat容器时内存泄漏

2017-11-14 18:35 513 查看
在完成定时任务的过程中,基本要求完成但是在项目停止的时候,Job 不能正常的去关闭,报出警告:

 org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [ROOT] appears to have started a thread named [***_QuartzSchedulerThread] but has failed to stop it. This is very likely to create a memory ...

原因:servlet容器关闭时发现Job定时器线程还在执行,对其无所适从,不懂怎么办只能强行关闭。

解决思路:在关闭容器时的contextDestroyed事件里检测ServletContext里Job  相关属性,找到Bean然后调用它的方法结束掉

代码:

   1、web.xml 增加一个listener



<listener>
<listener-class>com.***.elasticjob.AppContextListener</listener-class>
</listener>




2、AppContextListener 代码

public class AppContextListener extends ContextLoader implements ServletContextListener{
private static Logger logger = LoggerFactory.getLogger(AppContextListener.class);

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {

}

@Override
public void contextDestroyed(ServletContextEvent event) {
logger.info("Destroying Context...");

try {
WebApplicationContext context = (WebApplicationContext) event.getServletContext().getAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

String[] beanNames = context.getBeanDefinitionNames();

for(String beanName:beanNames)
{
if(beanName.contains("dangdang")&&beanName.contains("SpringJobScheduler")){
logger.info("发现dangdang定时任务beanName: "+beanName);
SpringJobScheduler scheduler = (SpringJobScheduler)context.getBean(beanName);
scheduler.getSchedulerFacade().shutdownInstance();
}
}
} catch (Exception e) {
logger.error("Error Destroying Context", e);
}
}
}


参考文献:

https://www.cnblogs.com/passedbylove/p/7580477.html[/code] 
http://blog.csdn.net/liujun_for_java/article/details/78101478

http://blog.csdn.net/dslztx/article/details/47276953




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息