Java Reference
In-Depth Information
// Clear the strong reference to the big object
bigObj = null;
// Check if weak reference has been queued
System.out.println("Before calling gc():");
printMessage(wr, q);
// Invoke garbage collector. If it runs, it will clear the weak reference
System.out.println("Invoking garbage collector...");
System.gc();
System.out.println("Garbage collector finished...");
// Check if weak reference has been queued
System.out.println("After calling gc():");
printMessage(wr, q);
}
public static void printMessage(WeakReference<BigObject> wr,
ReferenceQueue<BigObject> q) {
System.out.println("wr.get()= " + wr.get());
System.out.println("wr.isEnqueued()= " + wr.isEnqueued());
WeakReference<BigObject> temp = (WeakReference<BigObject>)q.poll();
if (temp == wr) {
System.out.println("q.poll() returned wr");
}
else {
System.out.println("q.poll()= " + temp);
}
}
}
Before calling gc():
wr.get()= BigObject: id = 131
wr.isEnqueued()= false
q.poll()= null
Invoking garbage collector...
Garbage collector finished...
After calling gc():
wr.get()= null
wr.isEnqueued()= false
q.poll()= null
finalize() called for id:131
Using the WeakReference Class
The only difference between a softly reachable and a weakly reachable object is that the garbage collector clears and
reclaims weakly reachable objects whenever it runs, whereas it uses some algorithm to decide whether it needs to
clear and reclaim a softly reachable object or not. In other words, the garbage collector may or may not reclaim a
softly reachable object, whereas it always reclaims a weakly reachable object.
 
Search WWH ::




Custom Search