今天我发现这篇博客文章 讨论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
课程?