本文介绍了Java:WeakHashMap的条目逐出时,谁更改大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近,我尝试弄清楚 WeakHashMap
的工作方式.如代码所示,在 System.gc()
和 size
被强引用之后, map.isEmpty()
将返回true,那么谁来更改大小?
Recently, I try to figure out how WeakHashMap
works. As code shows, map.isEmpty()
will return true after System.gc()
and size
is strong referenced, so who change size?
WeakHashMap<UniqueKey, BigImage> map = new WeakHashMap<>();
UniqueKey key = new UniqueKey("abc");
map.put(key, new BigImage());
BigImage value = map.get(key);
assertNotNull(value);
key = null;
System.gc();
Thread.sleep(1000);
assertTrue(map.isEmpty());
推荐答案
在内部查看实现:
public int size() {
if (size == 0)
return 0;
expungeStaleEntries();
return size;
}
专门用于 expungeStaleEntries
方法,该方法使用:
specifically for expungeStaleEntries
method that uses :
/**
* Reference queue for cleared WeakEntries
*/
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
在返回给您之前,此方法还会更新 size
.
This method also updates size
, before it is returned to you.
这篇关于Java:WeakHashMap的条目逐出时,谁更改大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!