SoftReference, WeakReference, and WeakHashMap in Java
What's the difference between SoftReferences and WeakReferences?
WeakReferences are cleared agressively; SoftReferences are not. Using a
SoftReference tells the garbage collector that you would like it to keep the
object around for a while, until memory considerations cause it to reclaim the
object. By contrast, using a WeakReference tells the garbage collector that
there's no reason to keep the object around any longer than necessary.
SoftReferences are primarily for implementing memory-senstive caches.
WeakReferences are primarily for associating extra information with an object (that's what WeakHashMap does).
Also note Sun bug 4239645,
which caused SoftReferences to act like WeakReferences in JDK 1.3.
What is WeakHashMap for?
It's not for caching. The idea is, suppose you have a bunch of objects of a certain class
that you can't extend, but you want to associate some other piece of information with each object.
You can use a Map, with the main object as the key and the extra info as the value. Using a WeakHashMap
for this will make sure that your Map won't cause a memory leak, because it won't hold a strong
reference to the main (key) object; this will allow the object to be garbage collected when it's no
longer needed. I believe that when the key is garbage collected, the value will soon be garbage
collected too, though not immediately.
More Info
See here or here.