为什么threadlocal不是弱引用
时间: 2023-10-14 18:05:12 浏览: 96
ThreadLocal并不是弱引用的主要原因是为了避免内存泄漏问题。如果ThreadLocal是弱引用,那么在外界对ThreadLocal的强引用回收后,ThreadLocal可能会被垃圾回收,但是与之对应的变量副本(即ThreadLocalMap中的value)还存在,并且无法被及时清理和回收,从而导致内存泄漏。为了避免这个问题,ThreadLocal使用了弱引用来解决。弱引用指向的对象在下次垃圾回收时会被回收,这样在ThreadLocal没有强引用指向时,ThreadLocalMap中的对应Entry的key也会被回收,从而确保变量副本也可以被及时清理和回收,避免内存泄漏的发生。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [关于ThreadLocal为什么采用弱引用的理解](https://blog.csdn.net/m0_49908016/article/details/120497770)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [ThreadLocal,你真的了解吗?](https://download.csdn.net/download/weixin_38607864/13742056)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文