WeakHashMap
public class WeakHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V> {
......
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
......
}
WeakHashMap和HashMap一样key和value的值都可以为null,并且也是无序的。但是HashMap的null是存在table[0]中的,这是固定的,并且null的hash为0,而在WeakHashMap中的null却没有存入table[0]中。 这是因为WeakHashMap对null值进行了包装:NULL_KEY
Entry 代码
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
V value;
final int hash;
Entry<K,V> next;
/**
* Creates new entry.
*/
Entry(Object key, V value,
ReferenceQueue<Object> queue,
int hash, Entry<K,V> next) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
......
private void expungeStaleEntries() {
// 遍历 ReferenceQueue 的 WeakReference 对象 Key 已经被GC回收的
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;
// 找到与 queue 中 WeakReference 对象对应的节点
if (p == e) {
// 判断 p 是不是单链表的首节点
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;
}
}
}
}
expungeStaleEntries调用关系
在 WeakHashMap 中几乎所有的操作(put,remove,get,size)都会涉及到消除操作,这也正体现了它的 weak。
NULL_KEY
上面提到了 WeakHashMap 的成员变量 NULL_KEY,当 key = null 时,会被其代替。
private static Object maskNull(Object key) {
return (key == null) ? NULL_KEY : key;
}
key 是弱引用,在其被 GC 回收后,对应的节点就会从(key-value)变成(null-value);
当要新增一个 key = null 的节点时,即 put(null,key)为了避免其被当成无用节点。null 会被
NULL_KEY 代替,变成(NULL_KEY,key)以此来区分。
实例
public class AnalyzeWeakHashMap {
public static void main(String[] args) throws Exception {
// test1();
// test2();
// test3();
//
test4();
}
private static void test4() {
List<WeakHashMap<byte[][], byte[][]>> maps = new ArrayList<WeakHashMap<byte[][], byte[][]>>();
for (int i = 0;; i++) {
WeakHashMap<byte[][], byte[][]> d = new WeakHashMap<byte[][], byte[][]>();
d.put(new byte[10000][10000], new byte[10000][10000]);
maps.add(d);
System.gc();
// 关键 -> 区别:
// System.err.print(i+",");
System.err.println( "size = " + d.size());
// 输出结果:
// size = 0
// ...
}
}
private static void test3() {
List<WeakHashMap<byte[][], byte[][]>> maps = new ArrayList<WeakHashMap<byte[][], byte[][]>>();
for (int i = 0;; i++) {
WeakHashMap<byte[][], byte[][]> d = new WeakHashMap<byte[][], byte[][]>();
d.put(new byte[10000][10000], new byte[10000][10000]);
maps.add(d);
System.gc();
System.err.print(i+",");
// 输出结果:
// 0,1,2,3,4,5,6,7,8,9,10,
// Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at Test3.main(Test3.java:10)
}
}
private static void test2() throws InterruptedException {
WeakHashMap<Object, String> wmap = new WeakHashMap<Object, String>();
wmap.put(new Object(), "a");
System.gc();
Thread.sleep(100);
System.out.println(wmap.size());
// 输出结果:0
}
private static void test1() throws InterruptedException {
WeakHashMap<Object, String> wmap = new WeakHashMap<Object, String>();
wmap.put(null, "a");
System.gc();
Thread.sleep(100);
System.out.println(wmap.size());
// 输出结果:1
}
}
实例 三,在程序运行不久后就 OOF 了。实例 四 ,则能一直运行下去。观察代码,发现它们的区别仅仅是最后调用了 size 方法。原因就在这里,size 方法会调用 expungeStaleEntries 清除无用节点,防止内存不断增加。
网友评论