ThreadLocal Resource Leak and WeakReference

后端 未结 7 1836
清酒与你
清酒与你 2020-12-30 03:12

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 (al

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 03:49

    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.

    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.

    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.


    Update: The cited problem only comes into play when the value stored in a ThreadLocal strongly references that ThreadLocal—sort of a circular reference.

    In this case, the value (a SimpleDateFormat), has no backwards reference to the ThreadLocal. There's no memory leak in this code.

提交回复
热议问题