Java編程WeakHashMap執行個體解析,javaweakhashmap

來源:互聯網
上載者:User

Java編程WeakHashMap執行個體解析,javaweakhashmap
簡述:

《Thinking in Java》第4版 P519 頁 WeakHashMap一章讀書筆記

WeakHashMap 用來儲存WeakReference,這一結構雲遜記憶體回收行程自動清理鍵和值

在添加鍵和值的操作時,映射會自動使用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的建構函式,進入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同時也構造出來了一個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()));}}}

可以預料到,部分由於String[] 保留了弱引用,所以輸出都是間隔3的

總結

以上就是本文關於Java編程WeakHashMap執行個體解析的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.