0

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}  

1 Answers1

0

A WeakHashMap is defined as having weak keys but not weak values:

Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.

If there is any reference to the key then the key and value pair will continue to exist in the map.

"Hemant" still exists because it is a string literal so in the string pool and 6 will exist because it's a small integer literal so it's in the integer pool.

The objects assigned to x and t don't exist because they're created with the new keyword which creates a new object and then they're set to null, removing the only reference to that object.

So because there are still references to "Hemant" and 6 then these keys and their values will stay in the map.

fgb
  • 18,439
  • 2
  • 38
  • 52