ThreadLocal垃圾回收 [英] ThreadLocal garbage collection

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

问题描述

来自javadoc


每个线程只要在线程还活着的情况下都隐含对其线程局部变量副本的隐式引用,并且ThreadLocal实例是可访问的;线程消失后,其线程本地实例的所有副本都将进行垃圾回收(除非存在对这些副本的其他引用)。

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; 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).

看来,仅当线程死亡时,才会对ThreadLocal变量引用的对象进行垃圾回收。但是,如果不再引用ThreadLocal变量 a 并接受垃圾回收该怎么办?如果持有 a 的线程仍然存在,是否仅对变量 a 进行对象引用会受到垃圾回收?

from that it seems that objects referenced by a ThreadLocal variable are garbage collected only when thread dies. But what if ThreadLocal variable a is no more referenced and is subject for garbage collection? Will object references only by variable a be subject to garbage collection if thread that holds a is still alive?

例如,以下类具有ThreadLocal变量:

for example there is following class with ThreadLocal variable:

public class Test {
    private static final ThreadLocal a = ...; // references object b
}

此类引用某个对象,而该对象没有其他对象引用。然后,在上下文取消部署时,应用程序类加载器成为垃圾收集的主题,但是线程来自线程池,因此它不会死亡。对象 b 会被垃圾回收吗?

This class references some object and this object has no other references to it. Then during context undeploy application classloader becomes a subject for garbage collection, but thread is from a thread pool so it does not die. Will object b be subject for garbage collection?

推荐答案

ThreadLocal变量是保持在线程中

ThreadLocal variables are hold in Thread

ThreadLocal.ThreadLocalMap threadLocals;

这是在第一个 ThreadLocal.set / get 在当前线程中的调用,并保持对 map 的引用,直到 Thread 处于活动状态。但是 ThreadLocalMap 使用 WeakReferences 作为密钥,因此当 ThreadLocal 是从其他任何地方引用的。有关详细信息,请参见 ThreadLocal.ThreadLocalMap javadoc

which is initialized lazily on first ThreadLocal.set/get invocation in the current thread and holds reference to the map until Thread is alive. However ThreadLocalMap uses WeakReferences for keys so its entries may be removed when ThreadLocal is referenced from nowhere else. See ThreadLocal.ThreadLocalMap javadoc for details

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

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