Java- WeakHashMap

WeakHashMap

  • It is exactly same as HashMap except following difference

  • In the case of HashMap eventhough Object doesn’t have any reference it is NOT elegible for gc() if it is associated with HashMap that is HashMap dominates Garbage collector

  • But the case of WeakHashMap if Object doesn’t have any references it is elegible for gc() eenthough Object associated with WeakHashMap that is Garbage collector dominates WeakHashMap

This Temp class is common for HashMap & WeakHapMap Demo’s

class Temp {
	@Override
	public String toString() {
 return "Temp";
	}
	@Override
	protected void finalize() throws Throwable {
 System.out.println("Finalize Called");
	}
}


HashMap Demo with GC

public class HashMapdemo {
	public static void main(String[] args) throws InterruptedException {
 HashMap m = new HashMap();
 Temp t = new Temp();
 m.put(t, "Satya");
 System.out.println(m);
 t=null;
 System.gc(); 
 Thread.sleep(5000);
//main Thread Sleeping for 5 seconds 
//Garbage collector takes control for 5 seconds
 System.out.println(m);
	}
}
-----------------------
{Temp=Satya}
{Temp=Satya}

In the above example Temp object is not eligible for gc() because it is associated with HashMap.in this case out put is {Temp=Satya} {Temp=Satya}


WeakHashMap Demo with GC

public class WeakHashMapdemo {
	public static void main(String[] args) throws InterruptedException {
 WeakHashMap m = new WeakHashMap();
 Temp t = new Temp();
 m.put(t, "Satya");
 System.out.println(m);
 t=null;
 System.gc(); 
 Thread.sleep(5000);
 System.out.println(m);
	}
}
-----------------------
{Temp=Satya}
Finalize Called
{}

In the above example Temp object is eligible for gc() because it is associated with HashMap.in this case out put is {Temp=Satya} Finalize Called {}