ThreadLocal&内存泄漏 [英] ThreadLocal & Memory Leak

查看:137
本文介绍了ThreadLocal&内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多个帖子中提到:不正确使用 ThreadLocal 会导致内存泄漏。我正在努力了解如何使用 ThreadLocal 来解决内存泄漏问题。

It is mentioned at multiple posts: improper use of ThreadLocal causes Memory Leak. I am struggling to understand how Memory Leak would happen using ThreadLocal.

我唯一想到的情况如下:

The only scenario I have figured out it as below:


网络-server维护一个Threads池(例如,用于servlet)。如果 ThreadLocal 中的变量未被删除,那么这些线程可能会造成内存泄漏,因为线程没有死亡。

A web-server maintains a pool of Threads (e.g. for servlets). Those threads can create memory leak if the variables in ThreadLocal are not removed because Threads do not die.

此方案未提及Perm Space内存泄漏。这是内存泄漏的唯一(主要)用例吗?

This scenario does not mention "Perm Space" memory leak. Is that the only (major) use case of memory leak?

推荐答案

PermGen穷举 ThreadLocal 通常是由类加载器泄漏引起的。


示例:

想象一下有一个池的应用服务器工作线程

它们将在应用程序服务器终止之前保持活动状态。

部署的Web应用程序使用静态 ThreadLocal 在其中一个类中,为了存储一些线程本地数据,另一个类的实例(让我们称之为 SomeClass )Web应用程序。这是在工作线程中完成的(例如,此操作源自 HTTP请求)。


重要:

根据定义,对的引用ThreadLocal value 保留,直到拥有线程死亡或者ThreadLocal本身不再可访问。


如果Web应用程序无法清除 ThreadLocal 关闭时的参考,会发生错误:

因为工作线程通常永远不会死亡,对 ThreadLocal 的引用是静态的, ThreadLocal 仍然引用 SomeClass 的实例,Web应用程序的类 - ,即使Web应用程序已停止!

As结果,Web应用程序的类加载器不能被垃圾回收,这就是mea ns 所有类(和所有静态数据)的Web应用程序仍然加载(这会影响PermGen内存池以及堆)。

Web应用程序的每次重新部署迭代都将增加permgen(和堆)的使用。


=>这是permgen泄漏


这种泄漏的一个常见例子是这个错误(同时修复)。

PermGen exhaustions in combination with ThreadLocal are often caused by classloader leaks.

An example:
Imagine an application server which has a pool of worker threads.
They will be kept alive until application server termination.
A deployed web application uses a static ThreadLocal in one of its classes in order to store some thread-local data, an instance of another class (lets call it SomeClass) of the web application. This is done within the worker thread (e.g. this action originates from a HTTP request).

Important:
By definition, a reference to a ThreadLocal value is kept until the "owning" thread dies or if the ThreadLocal itself is no longer reachable.

If the web application fails to clear the reference to the ThreadLocal on shutdown, bad things will happen:
Because the worker thread will usually never die and the reference to the ThreadLocal is static, the ThreadLocal value still references the instance of SomeClass, a web application's class - even if the web application has been stopped!

As a consequence, the web application's classloader cannot be garbage collected, which means that all classes (and all static data) of the web application remain loaded (this affects the PermGen memory pool as well as the heap).
Every redeployment iteration of the web application will increase permgen (and heap) usage.

=> This is the permgen leak

One popular example of this kind of leak is this bug in log4j (fixed in the meanwhile).

这篇关于ThreadLocal&内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆