gpt4 book ai didi

java - 自定义 ThreadLocal 类的 ThreadLocal 泄漏说明

转载 作者:行者123 更新时间:2023-11-28 22:48:39 29 4
gpt4 key购买 nike

我一直在读这个article关于 Tomcat 中的 ThreadLocal 泄漏。第一个示例包含以下代码:

public class MyCounter {
private int count = 0;

public void increment() {
count++;
}

public int getCount() {
return count;
}
}

public class MyThreadLocal extends ThreadLocal<MyCounter> {
}

public class LeakingServlet extends HttpServlet {
private static MyThreadLocal myThreadLocal = new MyThreadLocal();

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

MyCounter counter = myThreadLocal.get();
if (counter == null) {
counter = new MyCounter();
myThreadLocal.set(counter);
}

response.getWriter().println(
"The current thread served this servlet " + counter.getCount()
+ " times");
counter.increment();
}
}

它说所有的类都驻留在 webapp 中。然后它概述了以下对类加载器(不是 ThreadLocal)泄漏的解释,我不明白:

If the LeakingServlet is invoked at least once and the Thread that served it is not stopped, then we created a classloader leak !

The leak is caused because we have a custom class for the ThreadLocal instance, and also a custom class for the value bound to the Thread. Actually the important thing is that both classes were loaded by the webapp classloader.

ThreadLocal 泄漏的解释很糟糕。如果为请求提供服务的线程没有停止,我们怎么会有 ThreadLocal 泄漏(实际上文章说类加载器泄漏)?这是否意味着,如果 Thread 是 Tomcat 线程池的一部分,并且由于 MyThreadLocal.remove() 尚未关闭,则 MyCounter/MyThreadLocal 的 webapp 类加载器不能被垃圾回收,因为 Thread 已返回到游泳池?调用 MyThreadLocal.remove() 会解决这个问题吗?我不明白。

最佳答案

解释不正确:

The leak is caused because we have a custom class for the ThreadLocal instance

那部分是错误的。 Thread 类中的 ThreadLocalMap 使用 weakReferences 作为键,因此 threadLocal 实例是否为自定义类并不重要。我用我的自定义 ThreadLocal 类对此进行了测试,没有内存泄漏。

, and also a custom class for the value bound to the Thread.

这是正确的。对于值线程不使用弱引用,因此如果值是自定义类,将阻止它的类加载器被垃圾收集,这将导致该类加载器加载的所有类保留在内存中,直到线程从线程池中删除。

关于java - 自定义 ThreadLocal 类的 ThreadLocal 泄漏说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906166/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com