项目运行中日志打印
org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [xxx] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@4b0c8383]) and a value of type [com.xx.xxxx.Common] (value [com.xx.xxxx.Common@50a08aa6]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
但在web应用程序停止时未能将其删除。线程将随着时间的推移而更新,以尝试避免可能的内存泄漏。
查原因时因为tomcat 存在 threadlocals 内存泄漏风险,需要手动清理过期的request请求中创建的本地线程。
我的是springboot 项目,第一步:添加监听,第二步:自定义监听实现类
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Bean
public ServletListenerRegistrationBean listenerRegist() {
ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
srb.setListener(new ThreadLocalCleanListener());
return srb;
}
}
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import java.lang.ref.Reference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ThreadLocalCleanListener implements ServletRequestListener {
private void cleanUpThreadLocals() throws Exception {
Thread thread = Thread.currentThread();
Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Object threadLocalsInThread = threadLocalsField.get(thread);
Class threadLocalMapClass = Class
.forName("java.lang.ThreadLocal$ThreadLocalMap");
Method removeInThreadLocalMap = threadLocalMapClass.getDeclaredMethod(
"remove", ThreadLocal.class);
removeInThreadLocalMap.setAccessible(true);
Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
Object table = tableField.get(threadLocalsInThread);
for (int i = 0; i < Array.getLength(table); i++) {
Object entry = Array.get(table, i);
Method getMethod = Reference.class.getDeclaredMethod("get");
if (entry != null) {
ThreadLocal threadLocal = (ThreadLocal) getMethod.invoke(entry);
removeInThreadLocalMap.invoke(threadLocalsInThread, threadLocal);
}
}
}
@Override
public void requestDestroyed(ServletRequestEvent paramServletRequestEvent) {
try {
cleanUpThreadLocals();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void requestInitialized(ServletRequestEvent paramServletRequestEvent) {
}
}