1.类声明:
//key是保存在在WeakReference中的,因此若是key只在这个WeakReference中有引用,那么在下一次垃圾回收的时候就会将key进行回收,同时将这个WeakReference放到ReferenceQueue中。
public class WeakHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V> {}
2.变量:
//核心方法,查看引用队列,将队列中的引用所在的节点删除,节点对应的value置为null,方便垃圾回收。这个方法调用很多方法都会触发,比如get,put,size方法
private void expungeStaleEntries() {
for (Object x; (x = queue.poll()) != null; ) {
synchronized (queue) {
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) x;
int i = indexFor(e.hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> p = prev;
while (p != null) {
Entry<K,V> next = p.next;
if (p == e) {
if (prev == e)
table[i] = next;
else
prev.next = next;
// Must not null out e.next;
// stale entries may be in use by a HashIterator
e.value = null; // Help GC
size--;
break;
}
prev = p;
p = next;
}
}
}
}
参考文章:http://blog.csdn.net/u012403290/article/details/70158262