java - Why WeakReference to a WeakRef object is not garbage collected? -


while trying out examples weakreferences,i came across below scenario. creating hashmap , filled weak reference on employee object.now have 2 strong references, employee & weakreference . have made both null in try block.invoking gc explicity, block run.

so after gc run ,it supposed collect weakreference object in heap ,as there no strong reference it,but when print map still has key pointing old weakreference object.how possible?

            employee employee = new employee(11);             weakreference<employee>weakreference=new weakreference<employee>(employee);             map map = new hashmap<weakreference<employee>, string>();             map.put(weakreference, "test");             system.out.println(map);          try {             employee = null;             weakreference=null;             system.gc();         } catch (exception e) {             e.printstacktrace();         } {             system.out.println("inside finally");         }          system.out.println(map); 

and ouput

{java.lang.ref.weakreference@659e0bfd=test} inside {java.lang.ref.weakreference@659e0bfd=test} 

gc not delete weakreference itself, delete object references, map still contain weakreference. should check weakreference.get(). should return null after gc(). in case, make thread.sleep(1000) before check, gc has time job


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -