Web进程被kill掉后线程还在运行怎么办?

背景描述

系统有一个配置表,系统在启动后会启动一个线程,每隔5分钟将配置表里所有的数据更新到内存中。
系统是通过jenkins构建(直接kill掉Web进程,然后传入新的包再启动)的,每次在jenkins在构建系统后的5分钟内,系统都会报一次错:

Caused by: java.lang.IllegalStateException: EntityManagerFactory is closed
	at org.hibernate.internal.SessionFactoryImpl.validateNotClosed(SessionFactoryImpl.java:531)
	at org.hibernate.internal.SessionFactoryImpl.getCache(SessionFactoryImpl.java:830)
	at org.hibernate.internal.AbstractSharedSessionContract.<init>(AbstractSharedSessionContract.java:143)
	at org.hibernate.internal.AbstractSessionImpl.<init>(AbstractSessionImpl.java:29)
	at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:254)
	at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1290)
	at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:482)

原因分析

基于每次通过jenkins构建后系统只报一次异常和具体的堆栈信息,判断是更新配置信息到内存的线程没有在kill掉Web进程的时候停掉。

处理方案

1)使用Java EE5中的注解@PreDestroy;尝试过,没成功
2)使用Spring中的DisposableBean或配置destroy-method。(类实现 DisposableBean 接口,在 destroy() 方法中实现资源释放)使用该方式成功

参考

Tomcat热部署,Web工程中线程没有终止(https://www.cnblogs.com/shuimuzhushui/p/8490619.html)

原文地址:https://www.cnblogs.com/wsygdb/p/10951351.html