今天我发现了这篇博客文章,它讨论了在缓存中使用
WeakHashMap
的用法。事实上,存储的是键的弱引用而不是值,当引用不再存在时,整个键值对将从WeakHashMap
中移除。因此,会发生以下情况:WeakHashMap map = new WeakHashMap();
SomeClass myReference1 = ....
map.put(new Long(10), myReference1);
// do some stuff, but keep the myReference1 variable around!
SomeClass myReference2 = map.get(new Long(10)); // query the cache
if (myReference2 == null) {
// this is likely to happen because the reference to the first new Long(10) object
// might have been garbage-collected at this point
}
我很好奇什么情况下会利用WeakHashMap
类?
new Long(10)
。这样就足够了:map.get(10L);
- Matt Ball