When would you use a WeakHashMap or a WeakReference?
Solution 1:
One problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once.
Because an image cache is supposed to prevent us from reloading images when we don't absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. You are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory.
Understanding Weak References, Ethan Nicholas
Solution 2:
WeakReference
versus SoftReference
One distinction to be clear on is the difference between a WeakReference
and a SoftReference
.
Basically a WeakReference
will be GC-d by the JVM eagerly, once the referenced object has no hard references to it. A SoftReference
d object on the other hand, will tend to be left about by the garbage collector until it really needs to reclaim the memory.
A cache where the values are held inside WeakReference
s would be pretty useless (in a WeakHashMap
, it is the keys which are weakly referenced). SoftReferences
are useful to wrap the values around when you want to implement a cache which can grow and shrink with the available memory.