简体   繁体   English

如何正确处理ThreadLocal变量?

[英]How to properly dispose of ThreadLocal variables?

What is the cleanest way to dispose of ThreadLocal variables so that they are subject to garbage collection? 处置ThreadLocal变量以使其受到垃圾回收的最干净方法是什么? I read from the docs that: 我从文档中了解到:

...after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). ...在线程消失后,其所有线程本地实例的副本都将进行垃圾回收(除非存在对这些副本的其他引用)。

But sometimes threads can be pooled or are not expected to die. 但是有时候线程可以被合并,或者不会死亡。 Does the ThreadLocal#remove() method actually make the value subject to garbage collection? ThreadLocal#remove()方法是否实际上使值经受垃圾回收?

ThreadLocal.remove() is indeed removing a reference to the value... and if there is no more other living reference to it : the value will be soon garbage collected. ThreadLocal.remove()确实正在删除对该值的引用..., 如果没有其他活动引用,则该值将很快被垃圾回收。

When the thread died, the thread is removed form the GC-root... therefore the entry for the thread in the ThreadLocal is subject to GC... therefore the value for this entry in the ThreadLocal is subject to GC. 当线程死亡时,该线程将从GC根目录中删除...因此,ThreadLocal中线程的条目受GC的约束...因此,ThreadLocal中该条目的值受GC的约束。 But once again, if you have another living ref to the value : it won't be garbage collected. 但是再一次,如果您还有另一个对这个值的引用:它不会被垃圾收集。

If the thread is reused (because part of a pool or ...) : it is important to call remove() so that the value can be garbage collected, but also to avoid unexpected behavior when a new job is executed on a recycled thread (the new job don't need to know the value used by the previous job) 如果线程被重用(由于是池或...的一部分):调用remove()以便可以对值进行垃圾回收很重要,而且还可以避免在循环线程上执行新作业时发生意外行为(新工作不需要知道先前工作使用的值)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM