来自javadoc
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
引用的对象是否会被垃圾回收?
例如,有以下带有 ThreadLocal 变量的类:
public class Test {
private static final ThreadLocal a = ...; // references object b
}
这个类引用了一些对象,这个对象没有其他引用。然后在上下文取消部署期间,应用程序类加载器成为垃圾收集的主题,但线程来自线程池,因此它不会死亡。对象 b
会被垃圾回收吗?
最佳答案
ThreadLocal 变量保存在 Thread 中
ThreadLocal.ThreadLocalMap threadLocals;
在当前线程中第一次调用 ThreadLocal.set/get
时延迟初始化,并保持对 map
的引用,直到 Thread
处于 Activity 状态.但是,ThreadLocalMap
使用 WeakReferences
作为键,因此当 ThreadLocal
从别处引用时,它的条目可能会被删除。有关详细信息,请参阅 ThreadLocal.ThreadLocalMap
javadoc
关于java - ThreadLocal 垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17104452/