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.
A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
The weakref module allows the Python programmer to create weak references to objects. In the following, the term referent means the object which is referred to by a weak reference.
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With