簡述:
《Thinking in Java》第4版 P519 頁 WeakHashMap一章讀書筆記
WeakHashMap 用來保存WeakReference,這一結構云遜垃圾回收器自動清理鍵和值
在添加鍵和值的操作時,映射會自動使用WeakReference包裝它們,
見jdk源代碼,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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
1
2
3
4
|
/** * Reference queue for cleared WeakEntries */ private final ReferenceQueue<Object> queue = new ReferenceQueue<>(); |
點入new Entry
的構造函數,進入super頂層可以看到,
1
2
3
4
5
6
7
8
9
10
11
|
/** * 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對象
測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/anialy/article/details/39273345