Today I found this blog post which discussed usages of WeakHashMap
over cache. It was intrigued by the fact that not the values, but the keys are stored as weak references, and when the reference is no more alive, the entire key-value pair is removed from the WeakHashMap. This would therefore cause the following to happen:
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
}
I am curious what scenarios then would take advantage of the WeakHashMap
class?