Make delicious recipes!


WeakHashMap allows its keys to be garbage-collected if there is no other valid reference remaining in the code.

In the below code, we create a WeakHashMap and put two keys in it.
1st key is referenced by variable b throughout the life of the program and so it will not be garbage collected.
2nd key is not referenced by any variable and so its garbage collected as soon as GC runs.

Due to this, the 2nd box is garbage-collected and is removed from the map after System.gc().
import java.util.WeakHashMap;

public class WeakHashMapTest
    static WeakHashMap<Box, Integer> map = new WeakHashMap<Box, Integer>();   

    public static void main(String args[])
        Box b = new Box(1, 2, 3);
        map.put(b, 6);
        map.put(new Box(4, 5, 6), 15);
        /* Garbage-collect the second box */

    static class Box
        Integer a, b, c;

        public Box(Integer a, Integer b, Integer c)
            this.a = a; this.b = b; this.c = c;

        @Override public String toString()
            return "Box{" + a + "," + b + "," + c + "}";

{Box{1,2,3}=6, Box{4,5,6}=15}

Second box is garbage-collected 
after System.gc() and hence, its 
removed from the hash-map also.


Unexpected behavior of a HashMap

Because the garbage collector may discard keys at any time, a WeakHashMap behaves as if an unknown thread is silently removing entries from it. Even if the access to a WeakHashMap is synchronized, its size() and isEmpty() method can change values over time (as other threads die or lose reference to objects or the Garbage-Collector collects some keys in the background).

WeakHashMap implementation

WeakHashMap is very similar to a normal HashMap in terms of implementation except one important difference.
It has a ReferenceQueue which is automatically updated by the GC for any objects which are about to be garbage collected. This queue is checked by the function expungeStaleEntries() . If any entry is found in this queue, then expungeStaleEntries() removes the same from the hash-map also.
This function is called before most map functions like size(), get() etc. thus making sure that whatever entry has been garbage-collected by GC, is also removed before any kind of access.

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal