溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何理解ThreadLocal的Entry繼承WeakReference

發(fā)布時間:2021-10-09 15:27:08 來源:億速云 閱讀:172 作者:iii 欄目:編程語言

這篇文章主要介紹“如何理解ThreadLocal的Entry繼承WeakReference”,在日常操作中,相信很多人在如何理解ThreadLocal的Entry繼承WeakReference問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何理解ThreadLocal的Entry繼承WeakReference”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

導讀:ThreadLocal的Entry為什么要繼承WeakReference?弱引用GC的時候會回收?那么回收了,數(shù)據(jù)不會丟失嗎?

如何理解ThreadLocal的Entry繼承WeakReference

如何理解ThreadLocal的Entry繼承WeakReference

首先得看一眼WeakReference的代碼,它繼承自Reference,這里有個get()方法,代碼如下:

如何理解ThreadLocal的Entry繼承WeakReference

注意這一句:

If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null.

也就是說,referent這個字段會在GC時被修改,而它經(jīng)過GC后會變成null。

再看問題中說的這個Entry,代碼在這里:

如何理解ThreadLocal的Entry繼承WeakReference

注意這一句:

Note that null keys (i.e. entry.get() == null) mean that the key is no longer referenced, so the entry can be expunged from table.

這時得注意一件事,剛才提到ThreadLocal被GC后Entry中的reference就會變?yōu)?code>null,但是呢, Entry畢竟也是個對象,它除了會在GC時被改一下reference以外平平無奇,那么這里的value啥時候銷毀呢?

反正不會隨著ThreadLocal一起被刪就對了,甚至它能不能被銷毀都是個問題。GC線程是不可能在改reference時順便改value的,所以這個value只能是被咱自己刪。

那么就來看看ThreadLocal僅有的三個public的實例成員方法,也就是getset、remove,它們?nèi)齻€方法最后實際上會調(diào)用ThreadLocalMapgetEntry、set、remove這三個方法。

如何理解ThreadLocal的Entry繼承WeakReference

如何理解ThreadLocal的Entry繼承WeakReference

如何理解ThreadLocal的Entry繼承WeakReference

getEntry有可能通過getEntryAfterMiss調(diào)到expungeStaleEntry;set有可能調(diào)到replaceStaleEntry也有可能通過cleanSomeSlots調(diào)到expungeStaleEntry也有可能通過rehash調(diào)到expungeStaleEntries再調(diào)到expungeStaleEntry也有可能通過replaceStaleEntry調(diào)到cleanSomeSlotsexpungeStaleEntry;而remove也會調(diào)到expungeStaleEntry

總之,條條大路通羅馬,最后十有八九會跑到expungeStaleEntry里頭,而實際上這件事人家作者寫注釋的時候其實早就提醒過咱們了:

Note that null keys (i.e. entry.get() == null) mean that the key is no longer referenced, so the entry can be expunged from table.Such entries are referred to as "stale entries" in the code that follows.

如何理解ThreadLocal的Entry繼承WeakReference

expungeStaleEntry的實現(xiàn)

如何理解ThreadLocal的Entry繼承WeakReference

Entryvalue就是在這里被設(shè)置為null的,ThreadLocalMap中的table中的Entry也是在這里被設(shè)置為null的。

那么弱引用的作用是什么呢,只要去 ThreadLocal的源碼搜一下== null就能發(fā)現(xiàn)它出現(xiàn)的每一處都是在對reference作判斷,這代碼里就是通過判斷reference來判斷Entry還有用沒用的,最需要被GC的就是Entry中的value,而ThreadLocal本身是很小的,它里面只有一個threadLocalHashCode而已

到此,關(guān)于“如何理解ThreadLocal的Entry繼承WeakReference”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI