ThreadLocal资源泄漏和WeakReference [英] ThreadLocal Resource Leak and WeakReference
问题描述
我对 ThreadLocal 的理解有限它有资源泄漏问题。我认为可以通过正确使用来解决这个问题。使用ThreadLocal的WeakReferences (虽然我可能误解了这一点。)我想简单地使用一个模式或示例来正确使用带有WeakReference的ThreadLocal(如果存在)。例如,在这段代码片段中会引入WeakReference吗?
My limited understanding of ThreadLocal is that it has resource leak issues. I gather this problem can be remedied through proper use of WeakReferences with ThreadLocal (although I may have misunderstood this point.) I would simply like a pattern or example for correctly using ThreadLocal with WeakReference, if one exists. For instance, in this code snippet where would the WeakReference be introduced?
static class DateTimeFormatter {
private static final ThreadLocal<SimpleDateFormat> DATE_PARSER_THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy/MM/dd HH:mmz");
}
};
public String format(final Date date) {
return DATE_PARSER_THREAD_LOCAL.get().format(date);
}
public Date parse(final String date) throws ParseException
{
return DATE_PARSER_THREAD_LOCAL.get().parse(date);
}
}
推荐答案
ThreadLocal
在内部使用 WeakReference
。如果没有强引用 ThreadLocal
,它将被垃圾收集,即使各种线程通过 ThreadLocal存储值
。
ThreadLocal
uses a WeakReference
internally. If the ThreadLocal
is not strongly referenced, it will be garbage-collected, even though various threads have values stored via that ThreadLocal
.
此外, ThreadLocal
值实际存储在线程
;如果线程死亡,则收集与该线程通过 ThreadLocal
关联的所有值。
Additionally, ThreadLocal
values are actually stored in the Thread
; if a thread dies, all of the values associated with that thread through a ThreadLocal
are collected.
如果你有一个 ThreadLocal
作为最终的类成员,这是一个强引用,并且在卸载该类之前无法收集它。但这是任何类成员的工作方式,并且不被视为内存泄漏。
If you have a ThreadLocal
as a final class member, that's a strong reference, and it cannot be collected until the class is unloaded. But this is how any class member works, and isn't considered a memory leak.
更新:当存储在 ThreadLocal
中的值强烈引用 ThreadLocal
— sort时,引用的问题才会发挥作用循环引用。
Update: The cited problem only comes into play when the value stored in a ThreadLocal
strongly references that ThreadLocal
—sort of a circular reference.
在这种情况下,值(a SimpleDateFormat
)没有向后引用 ThreadLocal的
。此代码中没有内存泄漏。
In this case, the value (a SimpleDateFormat
), has no backwards reference to the ThreadLocal
. There's no memory leak in this code.
这篇关于ThreadLocal资源泄漏和WeakReference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!