Understanding the use of WeakHashMap as a cache

Understanding the use of WeakHashMap as a cache

WeakHashMap uses WeakReference for its keys. In order for an entry to be kept in such a map, the key object of the entry needs to be referenced somewhere outside of the map; otherwise, the entry is removed in the next garbage collection, according to the definition of WeakReference.

Suppose that you have put an entry of a key and a value into a WeakHashMap map, and the key uses object identity == for the equals() method. Now you want to get the value out using the key. According to the semantics of the equals() method, if you have the same key object, you can get the value; otherwise you don't. The behavior of WeakHashMap in this case is consistent with the semantics that, the value is indeed in the map for the former case, because you have the reference to the key outside of the map, otherwise you could not use it to get; the latter case is also consistent that, the value is free to be removed and may have already been removed from the map when you lose the key. So if key objects use object identity for equals(), WeakHashMap behaves similarly to HashMap, but with the added benifits that stale entries are removed automatically. This sounds like a cache.

But if key objects do not use object identity, WeakHashMap behaves differently from HashMap that entries may not hold and seem to be gone too fast. This may or may not be suitable for a cache.

In short, the proper use of WeakHashMap depends on the use of object identity for key objects. A possible good use of WeakHashMap inspired by this is an instance control pool or cache.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

To prevent automated spam submissions leave this field empty.