WeakReference in Java
WeakReference is related to garbage collection. Normally, object having one or more reference will not be eligible for garbage collection. Then above rule is not applicable when it is WeakReference. Weak references allow you to leverage the garbage collector’s ability to determine reachability for you, so you don’t have to do it yourself .If an object has only Weak reference with other objects, then its ready for garbage collection. A need for Weak references comes from a scenario in which you need to maintain metadata about an object for which you do not control.
Let’s now look at the below example. We have an Map with Objects where Key is Some Class Reference object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.HashMap; public class Test { public static void main(String args[]) { HashMap aMap = new HashMap(); Employee emp = new Employee("SARAL"); EmployeeVal val = new EmployeeVal("Developer"); aMap.put(emp, val); emp = null; System.gc(); System.out.println("Size of Map" + aMap.size()); } } |
Here the entries in map are not Garbage collected even if the reference to emp is null at line number 11. If the programs goes on forever then the entries are getting added to the map and at some time application will throw OutOfMemoryError.
WeakHashMap is one where the entries (key-to-value mappings) will be removed when it is no longer possible to retrieve them from the map.
Let me show the above example same with WeakHashMap.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.WeakHashMap; public class Test { public static void main(String args[]) { WeakHashMap aMap = new WeakHashMap(); Employee emp = new Employee("SARAL"); EmployeeVal val = new EmployeeVal("Developer"); aMap.put(emp, val); emp = null; System.gc(); int count = 0; while (0 != aMap.size()) { ++count; System.gc(); } System.out.println("Took " + count+ " calls to " + "System.gc() to result in weakHashMap size of : " + aMap.size()); } } |
Took 20 calls to System.gc() to result in aMap size of : 0.
Now when we make this emp = null then the Object of WeakHashMap is garbage collect. So there is no need to remove this entry explicitly. WeakHashMap has only weak references to the keys, not strong references like other Map classes. There are situations which you have to take care when the value or key is strongly referenced though you have used WeakHashMap. This can avoided by wrapping the object in a WeakReference.
Uses of Weak References:
- Caching : 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 . 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.
- WeakReference inside listeners : The listeners that are no longer active once the main reference to their target object is gone. Note that this does not mean the WeakReference is removed from the listeners list, cleaning up is still required but can be performed, for example, at scheduled times. This has also the effect of preventing the object listened to from holding strong references and eventually be a source of memory bloat. Example: Swing GUI components referring a model having a longer lifecycle than the window.While playing with listeners as described above we rapidly realised that objects get collected “immediately” from a user’s point of view.