Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WeakHashMap - what is its purpose and how should it be used correctly

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?

like image 964
Ivaylo Slavov Avatar asked Oct 24 '25 12:10

Ivaylo Slavov


1 Answers

When you want to attach metadata to an object for which you don't control the lifecycle. A common example is ClassLoader, though care must be taken to avoid creating a value->key reference cycle.

like image 72
Brett Kail Avatar answered Oct 27 '25 03:10

Brett Kail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!