7

I am going through the following post on Weak References in java :-

Understanding Weak References.

After going through the theoretical portion, trying to test weak reference for null condition. But, null check for weak reference never returns true in following code :-

package com.weak;

import java.lang.ref.WeakReference;

class Widget{}

public class WeakReferenceDemo {

    public static void main(String[] args) throws InterruptedException {

        Widget widget = new Widget() ;
        WeakReference<Widget> valueWrapper = new WeakReference<Widget>(widget) ;

        System.out.println( valueWrapper.get() );

        //here strong reference to object is lost
        widget = null ;

        int count = 0 ;

        //here checking for null condition
        while( valueWrapper.get() != null ){
            System.out.print(".");
            Thread.sleep(432) ;

            if(++count % 25 == 0)   System.out.println();
        }

        System.out.println( valueWrapper.get() );
    }
}

Please suggest, why valueWrapper.get() doesn't return null, though widget reference is assigned null value.

Thanks.

mogli
  • 1,549
  • 4
  • 29
  • 57
  • 4
    GC isn't reference counting, when you null that reference, the GC doesn't even know about it yet - it'll find it during the next GC cycle. – harold Oct 20 '11 at 17:31

2 Answers2

11

Rather than waiting for garbage collection, try calling it yourself with Runtime.getRuntime().gc(), then check the weak reference for null.

Weakly reachable objects are only reclaimed when GC runs. Since your program isn't instantiating any more objects onto the heap, this may never happen without manually asking it to run.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
1

WeakReference.get() doesn't return null until the garbage collector has got around to determining that the object is only weakly reachable. That might take some time.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151