1

Why is WeakReference to a WeakRef object not recovered?

 2 years ago
source link: https://www.codesd.com/item/why-is-weakreference-to-a-weakref-object-not-recovered.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why is WeakReference to a WeakRef object not recovered?

advertisements

While trying out some examples with WeakReferences,I just came across the below scenario. I am creating a hashmap and filled it with a weak reference on Employee object.Now I have two strong references, employee & weakReference . I have made both to null in the try block.Invoking the gc explicity, I get finally block run.

So after the gc run ,it is supposed to collect the weakReference object in the heap ,as there is no strong reference to it,But when I print the map it still has the key pointing to the old weakReference object.How is this 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();
        } finally {
            System.out.println("Inside finally");
        }

        System.out.println(map);

And the ouput is

{java.lang.ref.WeakReference@659e0bfd=Test}
Inside finally
{java.lang.ref.WeakReference@659e0bfd=Test}


GC will not delete WeakReference itself, it will delete only the object it references, so map will still contain the WeakReference. What you should check is weakReference.get(). This should return null after gc(). Just in case, make a Thread.sleep(1000) before check, so that GC has some time to do its job


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK