In below example, garbage collector is destroying an useless (refrence less) object if it is used as key in weakHashMap, which is alright.. but if any useless object as value, than why garbage collector is not destroying that object..
public class WeakHashMapDemo {
public static void main(String[] args) throws InterruptedException{
WeakHashMap whs=new WeakHashMap();
Temp t=new Temp();
Temp t1=new Temp();
Integer x=new Integer(5);
Integer y=6;
whs.put(t,"hemant");
whs.put("hemant", t1);
whs.put(x,"durga");
whs.put(y,"bacon");
System.out.println(whs);
t=null;
t1=null;
x=null;
y=null;
System.gc();
Thread.sleep(2000);
System.out.println(whs);
}
}
Temp class:-
class Temp{
@Override
public String toString() {
return "temp"; //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void finalize() throws Throwable {
System.out.println("finalize() mrthod is called");
}
}
output
{hemant=temp, 6=bacon, 5=durga, temp=hemant}
finalize() mrthod is called
{hemant=temp, 6=bacon}
acording to me output should be :-
{hemant=temp, 6=bacon, 5=durga, temp=hemant}
finalize() mrthod is called
{hemant=null}