WeakHashMap Example Java


WeakHashMap Example Java Tutorial

HashMap hm1 = new HashMap();

If hm1 is not used in the remaining part of the code, that is not referenced, the hm1 object is eligibile for garbage collection. That is, as long as hm1 is referenced (this is known as reference to hm1 and I call particulary here as strong reference. All the references we used so far in all the programs earlier are known as strong references, but simply we call as references), the hm1 is not deleted by garbage collector. Here, the whole object hm1 is garbage collected.

I change the above scenario here. Suppose hm1 has some elements and I do not use one element (that is, one element is not referenced in the remaining code), is it possible to garbage collect only the particular element and not all elements or not the whole hm1 object? This is not possible so far as our knowledge goes with garbage collection. We know, garbage collection takes place on the whole hm1 object but not on a single element.

But with WeakHashMap (introduced with JDK 1.2), it is possible to garbage collect even a single element (and not the whole hm1 object). It is because WeakHashMap has weak references to its elements. To give weak references, designers introduced a special class called java.lang.ref.WeakReference with JDK 1.2 with the following class signature.

public class WeakReference extends Reference

Following is the class signature of WeakHashMap

public class WeakHashMap extends AbstractMap implements Map

Being subclass of Map, WeakHashMap can make use of all the functionalities (methods) of Map. Following are a few methods that can be used with WeakHashMap.

clear(), containsKey(), entrySet(), isEmpty(), putAll(), size() and values() etc.

Following are constructors

  1. public WeakHashMap(): Creates a WeakHashMap object (without any elements placed by defualt and can be added later) with a default initial capacity of 16 and with a default load factor of 0.75.
  2. public WeakHashMap(int initialCapacity ic): Creates a WeakHashMap object (without any elements placed by default and can be added later) with initial capacity ic and with a default load factor of 0.75. The constructor throws IllegalArgumentException if the initial capacity is negative.
  3. public WeakHashMap(int initialCapacity ic, float loadFactor lf): Creates a WeakHashMap object (without any elements placed by default and can be added later) with initial capacity ic and load factor lf. The constructor throws IllegalArgumentException if the initial capacity or load factor is negative.
  4. public WeakHashMap(Map m1): Constructs a new WeakHashMap object with the same elements of map m1 by default placed. The initial capacity is sufficient to store the elements of m1. You can add extra elements later. The default load factor is 0.75. The constructor throws NullPointerException if m1 is null. Introduced with JDK 1.3.

Note: The weak reference is for the key only and for its associated value it is strong reference. When the key is removed, its associated value is also removed, obviously. That is, garbage collector determines to delete on key and not on value.

Applications of WeakHashMap

  1. Useful for catche and lookup storage.
  2. Useful for catching and storing meta data of the object.
  3. Useful for weakly referenced list of data where elements are dropped without side affeacts on the remaining elements.
  4. Useful to reduce memory leaks as elements are deleted without waiting for the whole object.
WeakHashMap Example Java
import java.util.*;
public class WHMDemo
{
  public static void main(String args[])
  {
    Map m1 = new WeakHashMap();

    Integer key1 = new Integer(10);   // used as keys
    Integer key2 = new Integer(20);

    Integer key3 = new Integer(30);    // used as values
    Integer key4 = new Integer(40);

    m1.put(key1, key3);
    m1.put(key2, key4);

    System.out.println("Value of key1: " + m1.get(key1));
    System.out.println("Value of key2: " + m1.get(key2));

    key1 = null;      // equivalent of not using in the remaining part of code
    // System.gc();   // let us see most probably garbage collection takes place.  
                      //This statement is not required with high speed processor
    
    System.out.println("Value of key1: " + m1.get(key1));
    System.out.println("Value of key2: " + m1.get(key2));
  }
}


WeakHashMap Example Java
Output screen on WeakHashMap Example Java

When key1 is made null, the associated value of key1 prints null but key2 is undisturbed.

For Map read interface Map Tutorial.

Pass your comments and suggestions to improve this tutorial "WeakHashMap Example Java".

2 thoughts on “WeakHashMap Example Java”

Leave a Comment

Your email address will not be published. Required fields are marked *