最近在看ThreadLocal源码的时候,看到当前线程对象有对ThreadLocalMap的引用。而ThreadLocalMap存放着线程本地对象以及线程本地对象的值。线程本地对象是弱引用的。当一个线程结束后,该线程对象进行内存回收?
它引用的ThreadLocalMap对象也进行内存回收?
明显的是ThreadLocalMap里的线程本地对象很可能被其它线程引用着,
线程本地对象的值也可能被其它线程引用着,
它们是如何被内存回收呢?

解决方案 »

  1.   

    建议先看下ThreadLocal的设计与使用(原理篇)
      

  2.   

    这里的弱引用的作用是不是这个?
    如果系统没有地方对这个线程本地对象保存引用了,
    那么这个变量就可以被内存回收,即使这个线程任然存在,ThreadLocalMap仍然存在。
      

  3.   


    你指的作用是什么,我知道的也不多,大家一起探讨只要ThreadLocal实例可访问且线程存活着,线程就会保持对thread-local变量拷贝的implicit引用线程结束,ThreadLocal就会被回收,除非这些thread-local变量的拷贝还被其它引用着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). 以上引自java doc,有什么问题吗
      

  4.   

    弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用的对象被垃圾回收的话,Java虚拟机就会把这个弱引用加入相关的引用队列中。
      

  5.   

    仅仅从上面我引用的那段话里看弱和强貌似没什么区别,普通的引用都是强引用吧? 对象失去引用不是会被回收吗? 不知道这个implicit reference的implicit作用体现在什么地方注:
    我不知道是不是可以称为弱和强
    因为这里是implicit和explicit的对比
    explicit reference:
    A reference that includes the exact location of the target element.implicit reference:
    (Computing) a reference to an object that does not give its exact page location, but assumes that the object is on the current page or is currently visible