一、前言
我發現Java很多開源架構都使用了WeakHashMap,剛開始沒怎麼去注意,隻知道它裡面存儲的值會随時間的推移慢慢減少(在 WeakHashMap 中,當某個“弱鍵”不再正常使用時,會被從WeakHashMap中被自動移除。更精确地說,對于一個給定的鍵,其映射的存在并不阻止垃圾回收器對該鍵的丢棄,這就使該鍵成為可終止的,被終止,然後被回收。某個鍵被終止時,它對應的鍵值對也就從映射中有效地移除了。這邊“弱鍵”的實作和清除,是通過WeakReference和ReferenceQueue實作的,如果對這部分不清楚,請參考我另外一篇博文:Java中強、軟、弱、虛引用),今天得空去看了一下源碼,也去查了一下資料,本想自己一步步解釋源碼,但看到一篇博文,寫的很好,遂不重複造輪子了,這邊直接轉載~
二、正文
在“前言”中有提到WeakHashMap的key是“弱鍵”,即是WeakReference類型的。ReferenceQueue是一個隊列,它會儲存被GC回收的“弱鍵”。實作步驟是:
- 建立WeakHashMap,将“鍵值對”添加到WeakHashMap中。實際上,WeakHashMap是通過數組table儲存Entry(鍵值對);每一個Entry實際上是一個單向連結清單,即Entry是鍵值對連結清單
- 當某“弱鍵”不再被其它對象引用,并被GC回收時。在GC回收該“弱鍵”時,這個“弱鍵”也同時會被添加到ReferenceQueue(queue)隊列中
- 當下一次我們需要操作WeakHashMap時,會先同步table和queue。table中儲存了全部的鍵值對,而queue中儲存被GC回收的鍵值對;同步它們,就是删除table中被GC回收的鍵值對。
這就是“弱鍵”如何被自動從WeakHashMap中删除的步驟了。和HashMap一樣,WeakHashMap是不同步的。可以使用 Collections.synchronizedMap 方法來構造同步的 WeakHashMap。
WeakHashMap的構造函數(有4個):
// 預設構造函數。
WeakHashMap()
// 指定“容量大小”的構造函數
WeakHashMap(int capacity)
// 指定“容量大小”和“加載因子”的構造函數
WeakHashMap(int capacity, float loadFactor)
// 包含“子Map”的構造函數
WeakHashMap(Map<? extends K, ? extends V> map)
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()
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> {}
WeakHashMap與Map關系如下圖:
從圖中可以看出:
- WeakHashMap繼承于AbstractMap,并且實作了Map接口
- 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清除”的“弱引用的鍵”
WeakHashMap的源碼進行解析(原文作者基于JDK1.6.0_45):
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 }
說明:WeakHashMap和HashMap都是通過"拉鍊法"實作的散清單。它們的源碼絕大部分内容都一樣,這裡就隻是對它們不同的部分就是說明。
WeakReference是“弱鍵”實作的哈希表。它這個“弱鍵”的目的就是:實作對“鍵值對”的動态回收。當“弱鍵”不再被使用到時,GC會回收它,WeakReference也會将“弱鍵”對應的鍵值對删除。
“弱鍵”是一個“弱引用(WeakReference)”,在Java中,WeakReference和ReferenceQueue 是聯合使用的。在WeakHashMap中亦是如此:如果弱引用所引用的對象被垃圾回收,Java虛拟機就會把這個弱引用加入到與之關聯的引用隊列中。 接着,WeakHashMap會根據“引用隊列”,來删除“WeakHashMap中已被GC回收的‘弱鍵’對應的鍵值對”。
另外,了解上面思想的重點是通過 expungeStaleEntries() 函數去了解。
(說明:原文有寫周遊WeakHashMap的示例,因個人覺得和HashMap的周遊沒什麼差別,這邊就不貼出來了,有興趣的同學請自行往“三、連結”部分的網址查詢)
WeakHashMap示例:
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.Date;
import java.lang.ref.WeakReference;
/**
* @desc WeakHashMap測試程式
*
* @author skywang
* @email [email protected]
*/
public class WeakHashMapTest {
public static void main(String[] args) throws Exception {
testWeakHashMapAPIs();
}
private static void testWeakHashMapAPIs() {
// 初始化3個“弱鍵”
String w1 = new String("one");
String w2 = new String("two");
String w3 = new String("three");
// 建立WeakHashMap
Map wmap = new WeakHashMap();
// 添加鍵值對
wmap.put(w1, "w1");
wmap.put(w2, "w2");
wmap.put(w3, "w3");
// 列印出wmap
System.out.printf("\nwmap:%s\n",wmap );
// containsKey(Object key) :是否包含鍵key
System.out.printf("contains key two : %s\n",wmap.containsKey("two"));
System.out.printf("contains key five : %s\n",wmap.containsKey("five"));
// containsValue(Object value) :是否包含值value
System.out.printf("contains value 0 : %s\n",wmap.containsValue(new Integer(0)));
// remove(Object key) : 删除鍵key對應的鍵值對
wmap.remove("three");
System.out.printf("wmap: %s\n",wmap );
// ---- 測試 WeakHashMap 的自動回收特性 ----
// 将w1設定null。
// 這意味着“弱鍵”w1再沒有被其它對象引用,調用gc時會回收WeakHashMap中與“w1”對應的鍵值對
w1 = null;
// 記憶體回收。這裡,會回收WeakHashMap中與“w1”對應的鍵值對
System.gc();
// 周遊WeakHashMap
Iterator iter = wmap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry en = (Map.Entry)iter.next();
System.out.printf("next : %s - %s\n",en.getKey(),en.getValue());
}
// 列印WeakHashMap的實際大小
System.out.printf(" after gc WeakHashMap size:%s\n", wmap.size());
}
}
輸出:
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
三、連結
http://blog.csdn.net/u012129558/article/details/51980883
四、聯系本人
為友善沒有部落格園賬号的讀者交流,特意建立一個企鵝群(純公益,非利益相關),讀者如果有對博文不明之處,歡迎加群交流:261746360,小杜比亞-部落格園