标签:
一、引言
Java中的引用类型由四种情况,强引用、软引用、弱引用、虚引用。关于这些的介绍可以参见鄙人另外一篇博文。 http://www.cnblogs.com/plxx/p/4217178.html
二、概述
WeakHashMap,在家族中和HashMap是同辈的。
public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
针对WeakHashMap --- An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.当key不再使用的时候,就会被自动清除。不再使用是个什么状态???当GC root 枚举不到的时候,就是认为此时可以被GC(finalizable -->finalized -->reclaimed 参阅)。
同HashMap一样,WeakHashMap允许<key,value>都为null,初始大小为16,load factor为0.75,不是线程安全的。
Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key
in a WeakHashMap at some later time and be surprised that its entry has been removed.
一旦Key被清除,就不可以再被创建,查询,稍后entry就会被移除。
Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference.
value objects do not strongly refer to their own keys, either directly or indirectly,
since that will prevent the keys from being discarded
其中的key存放的是weak reference.而value中存放的是strong reference,value不知直接或者间接地和key发生关联,否则会阻止key的清除。
三、查看源码
1 private void expungeStaleEntries() { 2 for (Object x; (x = queue.poll()) != null; ) { 3 synchronized (queue) { //将队列加锁控制 4 @SuppressWarnings("unchecked") 5 Entry<K,V> e = (Entry<K,V>) x; 6 int i = indexFor(e.hash, table.length); 7 8 Entry<K,V> prev = table[i]; //找到实体所在的桶号 9 Entry<K,V> p = prev;
//找到这个实体 10 while (p != null) { 11 Entry<K,V> next = p.next; 12 if (p == e) { 13 if (prev == e) 14 table[i] = next; 15 else 16 prev.next = next; 17 // Must not null out e.next; 18 // stale entries may be in use by a HashIterator 19 e.value = null; // Help GC 20 size--; 21 break; 22 }
//移除该实体--不可恢复 23 prev = p; 24 p = next; 25 } 26 } 27 } 28 }
expunge - Stale - Entries 擦除 陈旧 实体
在resize(),size(),getTables()的相关操作中都会调用该方法。将不使用的对象统统擦除。
标签:
原文地址:http://www.cnblogs.com/plxx/p/4655237.html