java集合13--WeakHashMap源碼詳解

轉載地址:http://blog.csdn.net/wangxiaotongfan/article/details/51346063

概要

這一章,我們對WeakHashMap進行學習。 
我們先對WeakHashMap有個整體認識,然後再學習它的源碼,最後再通過實例來學會使用WeakHashMap。

第1部分 WeakHashMap介紹 
第2部分 WeakHashMap數據結構 
第3部分 WeakHashMap源碼解析(基於JDK1.6.0_45) 
第4部分 WeakHashMap遍歷方式 
第5部分 WeakHashMap示例

第1部分 WeakHashMap介紹

WeakHashMap簡介

WeakHashMap 繼承於AbstractMap,實現了Map接口。

和HashMap一樣,WeakHashMap 也是一個散列表,它存儲的內容也是鍵值對(key-value)映射,而且鍵和值都可以是null。

不過WeakHashMap的鍵是“弱鍵”。在 WeakHashMap 中,當某個鍵不再正常使用時,會被從WeakHashMap中被自動移除。更精確地說,對於一個給定的鍵,其映射的存在並不阻止垃圾回收器對該鍵的丟棄,這就使該鍵成爲可終止的,被終止,然後被回收。某個鍵被終止時,它對應的鍵值對也就從映射中有效地移除了。

這個“弱鍵”的原理呢?大致上就是,通過WeakReference和ReferenceQueue實現的。 WeakHashMap的key是“弱鍵”,即是WeakReference類型的;ReferenceQueue是一個隊列,它會保存被GC回收的“弱鍵”。實現步驟是: 
(01) 新建WeakHashMap,將“鍵值對”添加到WeakHashMap中。實際上,WeakHashMap是通過數組table保存Entry(鍵值對);每一個Entry實際上是一個單向鏈表,即Entry是鍵值對鏈表。 
(02) 當某“弱鍵”不再被其它對象引用,並被GC回收時。在GC回收該“弱鍵”時,這個“弱鍵”也同時會被添加到ReferenceQueue(queue)隊列中。 
(03) 當下一次我們需要操作WeakHashMap時,會先同步table和queue。table中保存了全部的鍵值對,而queue中保存被GC回收的鍵值對;同步它們,就是刪除table中被GC回收的鍵值對。 
這就是“弱鍵”如何被自動從WeakHashMap中刪除的步驟了。

和HashMap一樣,WeakHashMap是不同步的。可以使用 Collections.synchronizedMap 方法來構造同步的 WeakHashMap。

WeakHashMap的構造函數

WeakHashMap共有4個構造函數,如下:

// 默認構造函數。
WeakHashMap()

// 指定“容量大小”的構造函數
WeakHashMap(int capacity)

// 指定“容量大小”和“加載因子”的構造函數
WeakHashMap(int capacity, float loadFactor)

// 包含“子Map”的構造函數
WeakHashMap(Map<? extends K, ? extends V> map)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

WeakHashMap的API
void                   clear()
Object                 clone()
boolean                containsKey(Object key)
boolean                containsValue(Object value)
Set<Entry<K, V>>       entrySet()
V                      get(Object key)
boolean                isEmpty()
Set<K>                 keySet()
V                      put(K key, V value)
void                   putAll(Map<? extends K, ? extends V> map)
V                      remove(Object key)
int                    size()
Collection<V>          values()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

第2部分 WeakHashMap數據結構

WeakHashMap的繼承關係如下

java.lang.Object
   ↳     java.util.AbstractMap<K, V>
         ↳     java.util.WeakHashMap<K, V>

public class WeakHashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V> {}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

WeakHashMap與Map關係如下圖:


從圖中可以看出: 
(01) WeakHashMap繼承於AbstractMap,並且實現了Map接口。 
(02) WeakHashMap是哈希表,但是它的鍵是”弱鍵”。WeakHashMap中保護幾個重要的成員變量:table, size, threshold, loadFactor, modCount, queue。 
  table是一個Entry[]數組類型,而Entry實際上就是一個單向鏈表。哈希表的”key-value鍵值對”都是存儲在Entry數組中的。 
  size是Hashtable的大小,它是Hashtable保存的鍵值對的數量。 
  threshold是Hashtable的閾值,用於判斷是否需要調整Hashtable的容量。threshold的值=”容量*加載因子”。 
  loadFactor就是加載因子。 
  modCount是用來實現fail-fast機制的 
  queue保存的是“已被GC清除”的“弱引用的鍵”。

第3部分 WeakHashMap源碼解析(基於JDK1.6.0_45)

下面對WeakHashMap的源碼進行說明

  1 package java.util;
  2 import java.lang.ref.WeakReference;
  3 import java.lang.ref.ReferenceQueue;
  4 
  5 public class WeakHashMap<K,V>
  6     extends AbstractMap<K,V>
  7     implements Map<K,V> {
  8 
  9     // 默認的初始容量是16,必須是2的冪。
 10     private static final int DEFAULT_INITIAL_CAPACITY = 16;
 11 
 12     // 最大容量(必須是2的冪且小於2的30次方,傳入容量過大將被這個值替換)
 13     private static final int MAXIMUM_CAPACITY = 1 << 30;
 14 
 15     // 默認加載因子
 16     private static final float DEFAULT_LOAD_FACTOR = 0.75f;
 17 
 18     // 存儲數據的Entry數組,長度是2的冪。
 19     // WeakHashMap是採用拉鍊法實現的,每一個Entry本質上是一個單向鏈表
 20     private Entry[] table;
 21 
 22     // WeakHashMap的大小,它是WeakHashMap保存的鍵值對的數量
 23     private int size;
 24 
 25     // WeakHashMap的閾值,用於判斷是否需要調整WeakHashMap的容量(threshold = 容量*加載因子)
 26     private int threshold;
 27 
 28     // 加載因子實際大小
 29     private final float loadFactor;
 30 
 31     // queue保存的是“已被GC清除”的“弱引用的鍵”。
 32     // 弱引用和ReferenceQueue 是聯合使用的:如果弱引用所引用的對象被垃圾回收,Java虛擬機就會把這個弱引用加入到與之關聯的引用隊列中
 33     private final ReferenceQueue<K> queue = new ReferenceQueue<K>();
 34 
 35     // WeakHashMap被改變的次數
 36     private volatile int modCount;
 37 
 38     // 指定“容量大小”和“加載因子”的構造函數
 39     public WeakHashMap(int initialCapacity, float loadFactor) {
 40         if (initialCapacity < 0)
 41             throw new IllegalArgumentException("Illegal Initial Capacity: "+
 42                                                initialCapacity);
 43         // WeakHashMap的最大容量只能是MAXIMUM_CAPACITY
 44         if (initialCapacity > MAXIMUM_CAPACITY)
 45             initialCapacity = MAXIMUM_CAPACITY;
 46 
 47         if (loadFactor <= 0 || Float.isNaN(loadFactor))
 48             throw new IllegalArgumentException("Illegal Load factor: "+
 49                                                loadFactor);
 50         // 找出“大於initialCapacity”的最小的2的冪
 51         int capacity = 1;
 52         while (capacity < initialCapacity)
 53             capacity <<= 1;
 54         // 創建Entry數組,用來保存數據
 55         table = new Entry[capacity];
 56         // 設置“加載因子”
 57         this.loadFactor = loadFactor;
 58         // 設置“WeakHashMap閾值”,當WeakHashMap中存儲數據的數量達到threshold時,就需要將WeakHashMap的容量加倍。
 59         threshold = (int)(capacity * loadFactor);
 60     }
 61 
 62     // 指定“容量大小”的構造函數
 63     public WeakHashMap(int initialCapacity) {
 64         this(initialCapacity, DEFAULT_LOAD_FACTOR);
 65     }
 66 
 67     // 默認構造函數。
 68     public WeakHashMap() {
 69         this.loadFactor = DEFAULT_LOAD_FACTOR;
 70         threshold = (int)(DEFAULT_INITIAL_CAPACITY);
 71         table = new Entry[DEFAULT_INITIAL_CAPACITY];
 72     }
 73 
 74     // 包含“子Map”的構造函數
 75     public WeakHashMap(Map<? extends K, ? extends V> m) {
 76         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, 16),
 77              DEFAULT_LOAD_FACTOR);
 78         // 將m中的全部元素逐個添加到WeakHashMap中
 79         putAll(m);
 80     }
 81 
 82     // 鍵爲null的mask值。
 83     // 因爲WeakReference中允許“null的key”,若直接插入“null的key”,將其當作弱引用時,會被刪除。
 84     // 因此,這裏對於“key爲null”的清空,都統一替換爲“key爲NULL_KEY”,“NULL_KEY”是“靜態的final常量”。
 85     private static final Object NULL_KEY = new Object();
 86 
 87     // 對“null的key”進行特殊處理
 88     private static Object maskNull(Object key) {
 89         return (key == null ? NULL_KEY : key);
 90     }
 91 
 92     // 還原對“null的key”的特殊處理
 93     private static <K> K unmaskNull(Object key) {
 94         return (K) (key == NULL_KEY ? null : key);
 95     }
 96 
 97     // 判斷“x”和“y”是否相等
 98     static boolean eq(Object x, Object y) {
 99         return x == y || x.equals(y);
100     }
101 
102     // 返回索引值
103     // h & (length-1)保證返回值的小於length
104     static int indexFor(int h, int length) {
105         return h & (length-1);
106     }
107 
108     // 清空table中無用鍵值對。原理如下:
109     // (01) 當WeakHashMap中某個“弱引用的key”由於沒有再被引用而被GC收回時,
110     //   被回收的“該弱引用key”也被會被添加到"ReferenceQueue(queue)"中。
111     // (02) 當我們執行expungeStaleEntries時,
112     //   就遍歷"ReferenceQueue(queue)"中的所有key
113     //   然後就在“WeakReference的table”中刪除與“ReferenceQueue(queue)中key”對應的鍵值對
114     private void expungeStaleEntries() {
115         Entry<K,V> e;
116         while ( (e = (Entry<K,V>) queue.poll()) != null) {
117             int h = e.hash;
118             int i = indexFor(h, table.length);
119 
120             Entry<K,V> prev = table[i];
121             Entry<K,V> p = prev;
122             while (p != null) {
123                 Entry<K,V> next = p.next;
124                 if (p == e) {
125                     if (prev == e)
126                         table[i] = next;
127                     else
128                         prev.next = next;
129                     e.next = null;  // Help GC
130                     e.value = null; //  "   "
131                     size--;
132                     break;
133                 }
134                 prev = p;
135                 p = next;
136             }
137         }
138     }
139 
140     // 獲取WeakHashMap的table(存放鍵值對的數組)
141     private Entry[] getTable() {
142         // 刪除table中“已被GC回收的key對應的鍵值對”
143         expungeStaleEntries();
144         return table;
145     }
146 
147     // 獲取WeakHashMap的實際大小
148     public int size() {
149         if (size == 0)
150             return 0;
151         // 刪除table中“已被GC回收的key對應的鍵值對”
152         expungeStaleEntries();
153         return size;
154     }
155 
156     public boolean isEmpty() {
157         return size() == 0;
158     }
159 
160     // 獲取key對應的value
161     public V get(Object key) {
162         Object k = maskNull(key);
163         // 獲取key的hash值。
164         int h = HashMap.hash(k.hashCode());
165         Entry[] tab = getTable();
166         int index = indexFor(h, tab.length);
167         Entry<K,V> e = tab[index];
168         // 在“該hash值對應的鏈表”上查找“鍵值等於key”的元素
169         while (e != null) {
170             if (e.hash == h && eq(k, e.get()))
171                 return e.value;
172             e = e.next;
173         }
174         return null;
175     }
176 
177     // WeakHashMap是否包含key
178     public boolean containsKey(Object key) {
179         return getEntry(key) != null;
180     }
181 
182     // 返回“鍵爲key”的鍵值對
183     Entry<K,V> getEntry(Object key) {
184         Object k = maskNull(key);
185         int h = HashMap.hash(k.hashCode());
186         Entry[] tab = getTable();
187         int index = indexFor(h, tab.length);
188         Entry<K,V> e = tab[index];
189         while (e != null && !(e.hash == h && eq(k, e.get())))
190             e = e.next;
191         return e;
192     }
193 
194     // 將“key-value”添加到WeakHashMap中
195     public V put(K key, V value) {
196         K k = (K) maskNull(key);
197         int h = HashMap.hash(k.hashCode());
198         Entry[] tab = getTable();
199         int i = indexFor(h, tab.length);
200 
201         for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
202             // 若“該key”對應的鍵值對已經存在,則用新的value取代舊的value。然後退出!
203             if (h == e.hash && eq(k, e.get())) {
204                 V oldValue = e.value;
205                 if (value != oldValue)
206                     e.value = value;
207                 return oldValue;
208             }
209         }
210 
211         // 若“該key”對應的鍵值對不存在於WeakHashMap中,則將“key-value”添加到table中
212         modCount++;
213         Entry<K,V> e = tab[i];
214         tab[i] = new Entry<K,V>(k, value, queue, h, e);
215         if (++size >= threshold)
216             resize(tab.length * 2);
217         return null;
218     }
219 
220     // 重新調整WeakHashMap的大小,newCapacity是調整後的單位
221     void resize(int newCapacity) {
222         Entry[] oldTable = getTable();
223         int oldCapacity = oldTable.length;
224         if (oldCapacity == MAXIMUM_CAPACITY) {
225             threshold = Integer.MAX_VALUE;
226             return;
227         }
228 
229         // 新建一個newTable,將“舊的table”的全部元素添加到“新的newTable”中,
230         // 然後,將“新的newTable”賦值給“舊的table”。
231         Entry[] newTable = new Entry[newCapacity];
232         transfer(oldTable, newTable);
233         table = newTable;
234 
235         if (size >= threshold / 2) {
236             threshold = (int)(newCapacity * loadFactor);
237         } else {
238             // 刪除table中“已被GC回收的key對應的鍵值對”
239             expungeStaleEntries();
240             transfer(newTable, oldTable);
241             table = oldTable;
242         }
243     }
244 
245     // 將WeakHashMap中的全部元素都添加到newTable中
246     private void transfer(Entry[] src, Entry[] dest) {
247         for (int j = 0; j < src.length; ++j) {
248             Entry<K,V> e = src[j];
249             src[j] = null;
250             while (e != null) {
251                 Entry<K,V> next = e.next;
252                 Object key = e.get();
253                 if (key == null) {
254                     e.next = null;  // Help GC
255                     e.value = null; //  "   "
256                     size--;
257                 } else {
258                     int i = indexFor(e.hash, dest.length);
259                     e.next = dest[i];
260                     dest[i] = e;
261                 }
262                 e = next;
263             }
264         }
265     }
266 
267     // 將"m"的全部元素都添加到WeakHashMap中
268     public void putAll(Map<? extends K, ? extends V> m) {
269         int numKeysToBeAdded = m.size();
270         if (numKeysToBeAdded == 0)
271             return;
272 
273         // 計算容量是否足夠,
274         // 若“當前實際容量 < 需要的容量”,則將容量x2。
275         if (numKeysToBeAdded > threshold) {
276             int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
277             if (targetCapacity > MAXIMUM_CAPACITY)
278                 targetCapacity = MAXIMUM_CAPACITY;
279             int newCapacity = table.length;
280             while (newCapacity < targetCapacity)
281                 newCapacity <<= 1;
282             if (newCapacity > table.length)
283                 resize(newCapacity);
284         }
285 
286         // 將“m”中的元素逐個添加到WeakHashMap中。
287         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
288             put(e.getKey(), e.getValue());
289     }
290 
291     // 刪除“鍵爲key”元素
292     public V remove(Object key) {
293         Object k = maskNull(key);
294         // 獲取哈希值。
295         int h = HashMap.hash(k.hashCode());
296         Entry[] tab = getTable();
297         int i = indexFor(h, tab.length);
298         Entry<K,V> prev = tab[i];
299         Entry<K,V> e = prev;
300 
301         // 刪除鏈表中“鍵爲key”的元素
302         // 本質是“刪除單向鏈表中的節點”
303         while (e != null) {
304             Entry<K,V> next = e.next;
305             if (h == e.hash && eq(k, e.get())) {
306                 modCount++;
307                 size--;
308                 if (prev == e)
309                     tab[i] = next;
310                 else
311                     prev.next = next;
312                 return e.value;
313             }
314             prev = e;
315             e = next;
316         }
317 
318         return null;
319     }
320 
321     // 刪除“鍵值對”
322     Entry<K,V> removeMapping(Object o) {
323         if (!(o instanceof Map.Entry))
324             return null;
325         Entry[] tab = getTable();
326         Map.Entry entry = (Map.Entry)o;
327         Object k = maskNull(entry.getKey());
328         int h = HashMap.hash(k.hashCode());
329         int i = indexFor(h, tab.length);
330         Entry<K,V> prev = tab[i];
331         Entry<K,V> e = prev;
332 
333         // 刪除鏈表中的“鍵值對e”
334         // 本質是“刪除單向鏈表中的節點”
335         while (e != null) {
336             Entry<K,V> next = e.next;
337             if (h == e.hash && e.equals(entry)) {
338                 modCount++;
339                 size--;
340                 if (prev == e)
341                     tab[i] = next;
342                 else
343                     prev.next = next;
344                 return e;
345             }
346             prev = e;
347             e = next;
348         }
349 
350         return null;
351     }
352 
353     // 清空WeakHashMap,將所有的元素設爲null
354     public void clear() {
355         while (queue.poll() != null)
356             ;
357 
358         modCount++;
359         Entry[] tab = table;
360         for (int i = 0; i < tab.length; ++i)
361             tab[i] = null;
362         size = 0;
363 
364         while (queue.poll() != null)
365             ;
366     }
367 
368     // 是否包含“值爲value”的元素
369     public boolean containsValue(Object value) {
370         // 若“value爲null”,則調用containsNullValue()查找
371         if (value==null)
372             return containsNullValue();
373 
374         // 若“value不爲null”,則查找WeakHashMap中是否有值爲value的節點。
375         Entry[] tab = getTable();
376         for (int i = tab.length ; i-- > 0 ;)
377             for (Entry e = tab[i] ; e != null ; e = e.next)
378                 if (value.equals(e.value))
379                     return true;
380         return false;
381     }
382 
383     // 是否包含null值
384     private boolean containsNullValue() {
385         Entry[] tab = getTable();
386         for (int i = tab.length ; i-- > 0 ;)
387             for (Entry e = tab[i] ; e != null ; e = e.next)
388                 if (e.value==null)
389                     return true;
390         return false;
391     }
392 
393     // Entry是單向鏈表。
394     // 它是 “WeakHashMap鏈式存儲法”對應的鏈表。
395     // 它實現了Map.Entry 接口,即實現getKey(), getValue(), setValue(V value), equals(Object o), hashCode()這些函數
396     private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
397         private V value;
398         private final int hash;
399         // 指向下一個節點
400         private Entry<K,V> next;
401 
402         // 構造函數。
403         Entry(K key, V value,
404           ReferenceQueue<K> queue,
405               int hash, Entry<K,V> next) {
406             super(key, queue);
407             this.value = value;
408             this.hash  = hash;
409             this.next  = next;
410         }
411 
412         public K getKey() {
413             return WeakHashMap.<K>unmaskNull(get());
414         }
415 
416         public V getValue() {
417             return value;
418         }
419 
420         public V setValue(V newValue) {
421         V oldValue = value;
422             value = newValue;
423             return oldValue;
424         }
425 
426         // 判斷兩個Entry是否相等
427         // 若兩個Entry的“key”和“value”都相等,則返回true。
428         // 否則,返回false
429         public boolean equals(Object o) {
430             if (!(o instanceof Map.Entry))
431                 return false;
432             Map.Entry e = (Map.Entry)o;
433             Object k1 = getKey();
434             Object k2 = e.getKey();
435             if (k1 == k2 || (k1 != null && k1.equals(k2))) {
436                 Object v1 = getValue();
437                 Object v2 = e.getValue();
438                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
439                     return true;
440             }
441             return false;
442         }
443 
444         // 實現hashCode()
445         public int hashCode() {
446             Object k = getKey();
447             Object v = getValue();
448             return  ((k==null ? 0 : k.hashCode()) ^
449                      (v==null ? 0 : v.hashCode()));
450         }
451 
452         public String toString() {
453             return getKey() + "=" + getValue();
454         }
455     }
456 
457     // HashIterator是WeakHashMap迭代器的抽象出來的父類,實現了公共了函數。
458     // 它包含“key迭代器(KeyIterator)”、“Value迭代器(ValueIterator)”和“Entry迭代器(EntryIterator)”3個子類。
459     private abstract class HashIterator<T> implements Iterator<T> {
460         // 當前索引
461         int index;
462         // 當前元素
463         Entry<K,V> entry = null;
464         // 上一次返回元素
465         Entry<K,V> lastReturned = null;
466         // expectedModCount用於實現fast-fail機制。
467         int expectedModCount = modCount;
468 
469         // 下一個鍵(強引用)
470         Object nextKey = null;
471 
472         // 當前鍵(強引用)
473         Object currentKey = null;
474 
475         // 構造函數
476         HashIterator() {
477             index = (size() != 0 ? table.length : 0);
478         }
479 
480         // 是否存在下一個元素
481         public boolean hasNext() {
482             Entry[] t = table;
483 
484             // 一個Entry就是一個單向鏈表
485             // 若該Entry的下一個節點不爲空,就將next指向下一個節點;
486             // 否則,將next指向下一個鏈表(也是下一個Entry)的不爲null的節點。
487             while (nextKey == null) {
488                 Entry<K,V> e = entry;
489                 int i = index;
490                 while (e == null && i > 0)
491                     e = t[--i];
492                 entry = e;
493                 index = i;
494                 if (e == null) {
495                     currentKey = null;
496                     return false;
497                 }
498                 nextKey = e.get(); // hold on to key in strong ref
499                 if (nextKey == null)
500                     entry = entry.next;
501             }
502             return true;
503         }
504 
505         // 獲取下一個元素
506         protected Entry<K,V> nextEntry() {
507             if (modCount != expectedModCount)
508                 throw new ConcurrentModificationException();
509             if (nextKey == null && !hasNext())
510                 throw new NoSuchElementException();
511 
512             lastReturned = entry;
513             entry = entry.next;
514             currentKey = nextKey;
515             nextKey = null;
516             return lastReturned;
517         }
518 
519         // 刪除當前元素
520         public void remove() {
521             if (lastReturned == null)
522                 throw new IllegalStateException();
523             if (modCount != expectedModCount)
524                 throw new ConcurrentModificationException();
525 
526             WeakHashMap.this.remove(currentKey);
527             expectedModCount = modCount;
528             lastReturned = null;
529             currentKey = null;
530         }
531 
532     }
533 
534     // value的迭代器
535     private class ValueIterator extends HashIterator<V> {
536         public V next() {
537             return nextEntry().value;
538         }
539     }
540 
541     // key的迭代器
542     private class KeyIterator extends HashIterator<K> {
543         public K next() {
544             return nextEntry().getKey();
545         }
546     }
547 
548     // Entry的迭代器
549     private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
550         public Map.Entry<K,V> next() {
551             return nextEntry();
552         }
553     }
554 
555     // WeakHashMap的Entry對應的集合
556     private transient Set<Map.Entry<K,V>> entrySet = null;
557 
558     // 返回“key的集合”,實際上返回一個“KeySet對象”
559     public Set<K> keySet() {
560         Set<K> ks = keySet;
561         return (ks != null ? ks : (keySet = new KeySet()));
562     }
563 
564     // Key對應的集合
565     // KeySet繼承於AbstractSet,說明該集合中沒有重複的Key。
566     private class KeySet extends AbstractSet<K> {
567         public Iterator<K> iterator() {
568             return new KeyIterator();
569         }
570 
571         public int size() {
572             return WeakHashMap.this.size();
573         }
574 
575         public boolean contains(Object o) {
576             return containsKey(o);
577         }
578 
579         public boolean remove(Object o) {
580             if (containsKey(o)) {
581                 WeakHashMap.this.remove(o);
582                 return true;
583             }
584             else
585                 return false;
586         }
587 
588         public void clear() {
589             WeakHashMap.this.clear();
590         }
591     }
592 
593     // 返回“value集合”,實際上返回的是一個Values對象
594     public Collection<V> values() {
595         Collection<V> vs = values;
596         return (vs != null ?  vs : (values = new Values()));
597     }
598 
599     // “value集合”
600     // Values繼承於AbstractCollection,不同於“KeySet繼承於AbstractSet”,
601     // Values中的元素能夠重複。因爲不同的key可以指向相同的value。
602     private class Values extends AbstractCollection<V> {
603         public Iterator<V> iterator() {
604             return new ValueIterator();
605         }
606 
607         public int size() {
608             return WeakHashMap.this.size();
609         }
610 
611         public boolean contains(Object o) {
612             return containsValue(o);
613         }
614 
615         public void clear() {
616             WeakHashMap.this.clear();
617         }
618     }
619 
620     // 返回“WeakHashMap的Entry集合”
621     // 它實際是返回一個EntrySet對象
622     public Set<Map.Entry<K,V>> entrySet() {
623         Set<Map.Entry<K,V>> es = entrySet;
624         return es != null ? es : (entrySet = new EntrySet());
625     }
626 
627     // EntrySet對應的集合
628     // EntrySet繼承於AbstractSet,說明該集合中沒有重複的EntrySet。
629     private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
630         public Iterator<Map.Entry<K,V>> iterator() {
631             return new EntryIterator();
632         }
633 
634         // 是否包含“值(o)”
635         public boolean contains(Object o) {
636             if (!(o instanceof Map.Entry))
637                 return false;
638             Map.Entry e = (Map.Entry)o;
639             Object k = e.getKey();
640             Entry candidate = getEntry(e.getKey());
641             return candidate != null && candidate.equals(e);
642         }
643 
644         // 刪除“值(o)”
645         public boolean remove(Object o) {
646             return removeMapping(o) != null;
647         }
648 
649         // 返回WeakHashMap的大小
650         public int size() {
651             return WeakHashMap.this.size();
652         }
653 
654         // 清空WeakHashMap
655         public void clear() {
656             WeakHashMap.this.clear();
657         }
658 
659         // 拷貝函數。將WeakHashMap中的全部元素都拷貝到List中
660         private List<Map.Entry<K,V>> deepCopy() {
661             List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(size());
662             for (Map.Entry<K,V> e : this)
663                 list.add(new AbstractMap.SimpleEntry<K,V>(e));
664             return list;
665         }
666 
667         // 返回Entry對應的Object[]數組
668         public Object[] toArray() {
669             return deepCopy().toArray();
670         }
671 
672         // 返回Entry對應的T[]數組(T[]我們新建數組時,定義的數組類型)
673         public <T> T[] toArray(T[] a) {
674             return deepCopy().toArray(a);
675         }
676     }
677 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463
  • 464
  • 465
  • 466
  • 467
  • 468
  • 469
  • 470
  • 471
  • 472
  • 473
  • 474
  • 475
  • 476
  • 477
  • 478
  • 479
  • 480
  • 481
  • 482
  • 483
  • 484
  • 485
  • 486
  • 487
  • 488
  • 489
  • 490
  • 491
  • 492
  • 493
  • 494
  • 495
  • 496
  • 497
  • 498
  • 499
  • 500
  • 501
  • 502
  • 503
  • 504
  • 505
  • 506
  • 507
  • 508
  • 509
  • 510
  • 511
  • 512
  • 513
  • 514
  • 515
  • 516
  • 517
  • 518
  • 519
  • 520
  • 521
  • 522
  • 523
  • 524
  • 525
  • 526
  • 527
  • 528
  • 529
  • 530
  • 531
  • 532
  • 533
  • 534
  • 535
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • 545
  • 546
  • 547
  • 548
  • 549
  • 550
  • 551
  • 552
  • 553
  • 554
  • 555
  • 556
  • 557
  • 558
  • 559
  • 560
  • 561
  • 562
  • 563
  • 564
  • 565
  • 566
  • 567
  • 568
  • 569
  • 570
  • 571
  • 572
  • 573
  • 574
  • 575
  • 576
  • 577
  • 578
  • 579
  • 580
  • 581
  • 582
  • 583
  • 584
  • 585
  • 586
  • 587
  • 588
  • 589
  • 590
  • 591
  • 592
  • 593
  • 594
  • 595
  • 596
  • 597
  • 598
  • 599
  • 600
  • 601
  • 602
  • 603
  • 604
  • 605
  • 606
  • 607
  • 608
  • 609
  • 610
  • 611
  • 612
  • 613
  • 614
  • 615
  • 616
  • 617
  • 618
  • 619
  • 620
  • 621
  • 622
  • 623
  • 624
  • 625
  • 626
  • 627
  • 628
  • 629
  • 630
  • 631
  • 632
  • 633
  • 634
  • 635
  • 636
  • 637
  • 638
  • 639
  • 640
  • 641
  • 642
  • 643
  • 644
  • 645
  • 646
  • 647
  • 648
  • 649
  • 650
  • 651
  • 652
  • 653
  • 654
  • 655
  • 656
  • 657
  • 658
  • 659
  • 660
  • 661
  • 662
  • 663
  • 664
  • 665
  • 666
  • 667
  • 668
  • 669
  • 670
  • 671
  • 672
  • 673
  • 674
  • 675
  • 676
  • 677

說明:WeakHashMap和HashMap都是通過”拉鍊法”實現的散列表。它們的源碼絕大部分內容都一樣,這裏就只是對它們不同的部分就是說明。

WeakReference是“弱鍵”實現的哈希表。它這個“弱鍵”的目的就是:實現對“鍵值對”的動態回收。當“弱鍵”不再被使用到時,GC會回收它,WeakReference也會將“弱鍵”對應的鍵值對刪除。 
“弱鍵”是一個“弱引用(WeakReference)”,在Java中,WeakReference和ReferenceQueue 是聯合使用的。在WeakHashMap中亦是如此:如果弱引用所引用的對象被垃圾回收,Java虛擬機就會把這個弱引用加入到與之關聯的引用隊列中。 接着,WeakHashMap會根據“引用隊列”,來刪除“WeakHashMap中已被GC回收的‘弱鍵’對應的鍵值對”。 
另外,理解上面思想的重點是通過 expungeStaleEntries() 函數去理解。

第4部分 WeakHashMap遍歷方式

4.1 遍歷WeakHashMap的鍵值對

第一步:根據entrySet()獲取WeakHashMap的“鍵值對”的Set集合。 
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。

// 假設map是WeakHashMap對象
// map中的key是String類型,value是Integer類型
Integer integ = null;
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
    Map.Entry entry = (Map.Entry)iter.next();
    // 獲取key
    key = (String)entry.getKey();
        // 獲取value
    integ = (Integer)entry.getValue();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4.2 遍歷WeakHashMap的鍵

第一步:根據keySet()獲取WeakHashMap的“鍵”的Set集合。 
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。

// 假設map是WeakHashMap對象
// map中的key是String類型,value是Integer類型
String key = null;
Integer integ = null;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
        // 獲取key
    key = (String)iter.next();
        // 根據key,獲取value
    integ = (Integer)map.get(key);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4.3 遍歷WeakHashMap的值

第一步:根據value()獲取WeakHashMap的“值”的集合。 
第二步:通過Iterator迭代器遍歷“第一步”得到的集合。

// 假設map是WeakHashMap對象
// map中的key是String類型,value是Integer類型
Integer value = null;
Collection c = map.values();
Iterator iter= c.iterator();
while (iter.hasNext()) {
    value = (Integer)iter.next();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

WeakHashMap遍歷測試程序如下:

  1 import java.util.Map;
  2 import java.util.Random;
  3 import java.util.Iterator;
  4 import java.util.WeakHashMap;
  5 import java.util.HashSet;
  6 import java.util.Map.Entry;
  7 import java.util.Collection;
  8 
  9 /*
 10  * @desc 遍歷WeakHashMap的測試程序。
 11  *   (01) 通過entrySet()去遍歷key、value,參考實現函數:
 12  *        iteratorHashMapByEntryset()
 13  *   (02) 通過keySet()去遍歷key、value,參考實現函數:
 14  *        iteratorHashMapByKeyset()
 15  *   (03) 通過values()去遍歷value,參考實現函數:
 16  *        iteratorHashMapJustValues()
 17  *
 18  * @author skywang
 19  */
 20 public class WeakHashMapIteratorTest {
 21 
 22     public static void main(String[] args) {
 23         int val = 0;
 24         String key = null;
 25         Integer value = null;
 26         Random r = new Random();
 27         WeakHashMap map = new WeakHashMap();
 28 
 29         for (int i=0; i<12; i++) {
 30             // 隨機獲取一個[0,100)之間的數字
 31             val = r.nextInt(100);
 32             
 33             key = String.valueOf(val);
 34             value = r.nextInt(5);
 35             // 添加到WeakHashMap中
 36             map.put(key, value);
 37             System.out.println(" key:"+key+" value:"+value);
 38         }
 39         // 通過entrySet()遍歷WeakHashMap的key-value
 40         iteratorHashMapByEntryset(map) ;
 41         
 42         // 通過keySet()遍歷WeakHashMap的key-value
 43         iteratorHashMapByKeyset(map) ;
 44         
 45         // 單單遍歷WeakHashMap的value
 46         iteratorHashMapJustValues(map);        
 47     }
 48     
 49     /*
 50      * 通過entry set遍歷WeakHashMap
 51      * 效率高!
 52      */
 53     private static void iteratorHashMapByEntryset(WeakHashMap map) {
 54         if (map == null)
 55             return ;
 56 
 57         System.out.println("\niterator WeakHashMap By entryset");
 58         String key = null;
 59         Integer integ = null;
 60         Iterator iter = map.entrySet().iterator();
 61         while(iter.hasNext()) {
 62             Map.Entry entry = (Map.Entry)iter.next();
 63             
 64             key = (String)entry.getKey();
 65             integ = (Integer)entry.getValue();
 66             System.out.println(key+" -- "+integ.intValue());
 67         }
 68     }
 69 
 70     /*
 71      * 通過keyset來遍歷WeakHashMap
 72      * 效率低!
 73      */
 74     private static void iteratorHashMapByKeyset(WeakHashMap map) {
 75         if (map == null)
 76             return ;
 77 
 78         System.out.println("\niterator WeakHashMap By keyset");
 79         String key = null;
 80         Integer integ = null;
 81         Iterator iter = map.keySet().iterator();
 82         while (iter.hasNext()) {
 83             key = (String)iter.next();
 84             integ = (Integer)map.get(key);
 85             System.out.println(key+" -- "+integ.intValue());
 86         }
 87     }
 88     
 89 
 90     /*
 91      * 遍歷WeakHashMap的values
 92      */
 93     private static void iteratorHashMapJustValues(WeakHashMap map) {
 94         if (map == null)
 95             return ;
 96         
 97         Collection c = map.values();
 98         Iterator iter= c.iterator();
 99         while (iter.hasNext()) {
100             System.out.println(iter.next());
101        }
102     }
103 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103

第5部分 WeakHashMap示例

下面通過實例來學習如何使用WeakHashMap

 1 import java.util.Iterator;
 2 import java.util.Map;
 3 import java.util.WeakHashMap;
 4 import java.util.Date;
 5 import java.lang.ref.WeakReference;
 6 
 7 /**
 8  * @desc WeakHashMap測試程序
 9  *
10  * @author skywang
11  * @email [email protected]
12  */
13 public class WeakHashMapTest {
14 
15     public static void main(String[] args) throws Exception {
16         testWeakHashMapAPIs();
17     }
18 
19     private static void testWeakHashMapAPIs() {
20         // 初始化3個“弱鍵”
21         String w1 = new String("one");
22         String w2 = new String("two");
23         String w3 = new String("three");
24         // 新建WeakHashMap
25         Map wmap = new WeakHashMap();
26 
27         // 添加鍵值對
28         wmap.put(w1, "w1");
29         wmap.put(w2, "w2");
30         wmap.put(w3, "w3");
31 
32         // 打印出wmap
33         System.out.printf("\nwmap:%s\n",wmap );
34 
35         // containsKey(Object key) :是否包含鍵key
36         System.out.printf("contains key two : %s\n",wmap.containsKey("two"));
37         System.out.printf("contains key five : %s\n",wmap.containsKey("five"));
38 
39         // containsValue(Object value) :是否包含值value
40         System.out.printf("contains value 0 : %s\n",wmap.containsValue(new Integer(0)));
41 
42         // remove(Object key) : 刪除鍵key對應的鍵值對
43         wmap.remove("three");
44 
45         System.out.printf("wmap: %s\n",wmap );
46 
47 
48 
49         // ---- 測試 WeakHashMap 的自動回收特性 ----
50     
51         // 將w1設置null。
52         // 這意味着“弱鍵”w1再沒有被其它對象引用,調用gc時會回收WeakHashMap中與“w1”對應的鍵值對
53         w1 = null;
54         // 內存回收。這裏,會回收WeakHashMap中與“w1”對應的鍵值對
55         System.gc();
56 
57         // 遍歷WeakHashMap
58         Iterator iter = wmap.entrySet().iterator();
59         while (iter.hasNext()) {
60             Map.Entry en = (Map.Entry)iter.next();
61             System.out.printf("next : %s - %s\n",en.getKey(),en.getValue());
62         }
63         // 打印WeakHashMap的實際大小
64         System.out.printf(" after gc WeakHashMap size:%s\n", wmap.size());
65     }
66 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

運行結果:

wmap:{three=w3, one=w1, two=w2}
contains key two : true
contains key five : false
contains value 0 : false
wmap: {one=w1, two=w2}
next : two - w2
 after gc WeakHashMap size:1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章