您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何理解ThreadLocal的Entry繼承WeakReference”,在日常操作中,相信很多人在如何理解ThreadLocal的Entry繼承WeakReference問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何理解ThreadLocal的Entry繼承WeakReference”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
導讀:ThreadLocal的Entry為什么要繼承WeakReference?弱引用GC的時候會回收?那么回收了,數(shù)據(jù)不會丟失嗎?
首先得看一眼WeakReference
的代碼,它繼承自Reference
,這里有個get()
方法,代碼如下:
注意這一句:
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
,代碼在這里:
注意這一句:
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
的實例成員方法,也就是get
、set
、remove
,它們?nèi)齻€方法最后實際上會調(diào)用ThreadLocalMap
的getEntry
、set
、remove
這三個方法。
getEntry
有可能通過getEntryAfterMiss
調(diào)到expungeStaleEntry
;set
有可能調(diào)到replaceStaleEntry
也有可能通過cleanSomeSlots
調(diào)到expungeStaleEntry
也有可能通過rehash
調(diào)到expungeStaleEntries
再調(diào)到expungeStaleEntry
也有可能通過replaceStaleEntry
調(diào)到cleanSomeSlots
和expungeStaleEntry
;而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.
expungeStaleEntry
的實現(xiàn)
而Entry
的value
就是在這里被設(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>
免責聲明:本站發(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)容。