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.
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.