Java編程WeakHashMap實例解析
簡述:
《Thinking in Java》第4版 P519 頁 WeakHashMap一章讀書筆記
WeakHashMap 用來保存WeakReference,這一結(jié)構(gòu)云遜垃圾回收器自動清理鍵和值
在添加鍵和值的操作時,映射會自動使用WeakReference包裝它們,
見jdk源代碼,
public V put(K key, V value) { Object k = maskNull(key); int h = hash(k); Entry<K,V>[] tab = getTable(); int i = indexFor(h, tab.length); for (Entry<K,V> e = tab[i]; e != null; e = e.next) { if (h == e.hash && eq(k, e.get())) { V oldValue = e.value; if (value != oldValue) e.value = value; return oldValue; } } modCount++; Entry<K,V> e = tab[i]; tab[i] = new Entry<>(k, value, queue, h, e); if (++size >= threshold) resize(tab.length * 2); return null; }
其中new Entry<>(k, value, queue, h, e)
一行使用了ReferenceQueue
/** * Reference queue for cleared WeakEntries */ private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
點入new Entry
的構(gòu)造函數(shù),進入super頂層可以看到,
/** * Creates a new weak reference that refers to the given object and is * registered with the given queue. * * @param referent object the new weak reference will refer to * @param q the queue with which the reference is to be registered, * or <tt>null</tt> if registration is not required */ public WeakReference(T referent, ReferenceQueue<? super T> q) { super(referent, q); }
這里new Entry
同時也構(gòu)造出來了一個WeakRefence對象
測試:
package com.anialy.test.data_structure.map; import java.util.Iterator; import java.util.WeakHashMap; public class WeakHashMapTest { public static void main(String[] args) { WeakHashMap wmap = new WeakHashMap<String, Object>(); final int SIZE = 10; String[] str = new String[SIZE]; for (int i=0; i<SIZE; i++){ String key = Integer.toString(i); String value = Integer.toString(i); // 每隔3個保留一個引用 if(i % 3 == 0) str[i] = key; wmap.put(key, value); } System.gc(); Iterator iter = wmap.keySet().iterator(); while(iter.hasNext()){ System.out.println(wmap.get(iter.next())); } } }
可以預(yù)料到,部分由于String[] 保留了弱引用,所以輸出都是間隔3的
總結(jié)
以上就是本文關(guān)于Java編程WeakHashMap實例解析的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
使用Java代碼實現(xiàn)RocketMQ的生產(chǎn)與消費消息
這篇文章介紹一下其他的小組件以及使用Java代碼實現(xiàn)生產(chǎn)者對消息的生成,消費者消費消息等知識點,并通過代碼示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07Java8新特性之空指針異常的克星Optional類的實現(xiàn)
這篇文章主要介紹了Java8新特性之空指針異常的克星Optional類的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10springboot啟動不加載bootstrap.yml文件的問題
這篇文章主要介紹了springboot啟動不加載bootstrap.yml文件的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12java拷貝指定目錄下所有內(nèi)容到minIO代碼實例
這篇文章主要介紹了java拷貝指定目錄下所有內(nèi)容到minIO代碼實例,創(chuàng)建桶 直接使用工具類先判斷,再創(chuàng)建即可,創(chuàng)建文件夾,需要注意以"/"結(jié)尾,實際也是在minIO上創(chuàng)建文件,只是作為目錄的表現(xiàn)形式展示,需要的朋友可以參考下2024-01-01