What is WeakHashMap in Java?

 

What is WeakHashMap in Java?

What is WeakHashMap in Java?

What is WeakHashMap in Java?
  • It is exactly same as HashMap except for the following difference:-
  • In the case of HashMap even though object doesn’t have any reference it is not eligible for GC. If it is associated with HashMap that is HashMap dominates Garbage collector.
  • But in the case of WeakHashMap, if the object doesn’t contain any references it is eligible for GC even though object associated with WeakHashMap that is Garbage collector dominates WeakHashMap.
  • A WeakHashMap is a hash map where the keys are stored in weak references. That is, if you stop using the key object, the entry may be reclaimed. As you note, this means that it’s not useful for its apparent purpose, as a cache. That would be a map that used weak references to values, not to keys.
  • Rather, it’s used like a table, to attach information to objects. For example, suppose you have a bunch of open Sockets, and you want to include, say, a name for each one. You can’t add a field to the Socket So you could use a WeakHashMap
  • We can use a WeakHashmap to reduce the chance of a memory leak as a result of caching some object. WeakHashMap will automatically remove entries whenever all references to the key are removed.
  • In a WeakHashMap an entry will automatically be removed when its key is no longer in ordinary use, means there is no single Reference that point to that key. once the GC process discards a key, then its entry will effectively be removed from the map, so this class behaves somewhat differently from other Map implementations.
package com.java4us;

import java.util.HashMap;

class Test {
    public static void main(String[] args) throws InterruptedException {
        HashMap map = new HashMap();
        Test t = new Test();
        map.put(t, "Raja");
        System.out.println(map);
        t = null;
        System.gc();
        Thread.sleep(2000);
        System.out.println(map);
    }

    @Override
    public String toString() {
        return "Test[]";
    }

    public void finalize() {
        System.out.println("Finalized method called");
    }

}
  • In the above example Test object not eligible for GC because it is associated with HashMap.
  • In the above program if we replace HashMap with WeakHashMap then Test object eligible for GC.

3 comments

  1. Raman K Pandita

    Please update name to ‘WeakHashMap’ instead of ‘WeekHashMap’.

  2. Remarkable! Its really awesome post, I have got much clear idea about from this article.

Leave a Reply

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

*