One Common use of WeakReferences and WeakHashMaps in particular is for
adding properties to objects. Occasionally you want to add some
functionality or data to an object but subclassing and/or composition
are not an option in that case the obvious thing to do would be to
create a hashmap linking the object you want to extend to the property
you want to add. then whenever you need the property you can just look
it up in the map. However, if the objects you are adding properties to
tend to get destroyed and created a lot, you can end up with a lot of
old objects in your map taking up a lot of memory
If you use a WeakHashMap instead the objects will leave your map as
soon as they are no longer used by the rest of your program, which is
the desired behavior.
The key of a WeakHashMap
has weak reference. If the key has been garbage collected, then the entry in WeakHashMap
object will automatically be deleted. It does not happen in normal HashMap
. The entry will not be deleted if the key is garbage collected.
In the example I have taken one HashMap
and one WeakHashMap
. I will put entry in both the object and then later we will make the reference key as null
and then garbage collected. And again check the entry. In the HashMap
object entry will be there but in WeakHashMap
object there will not be entry present.
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class WeakHashMapTest {
public static void main(String[] args) {
Map hashMap= new HashMap();
Map weakHashMap = new WeakHashMap();
String keyHashMap = new String("keyHashMap");
String keyWeakHashMap = new String("keyWeakHashMap");
hashMap.put(keyHashMap, "Ankita");
weakHashMap.put(keyWeakHashMap, "Atul");
System.gc();
System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
keyHashMap = null;
keyWeakHashMap = null;
System.gc();
System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
}
}
The output would be:
Before: hash map value:Ankita and weak hash map value:Atul
After: hash map value:Ankita and weak hash map value:null
More info: