Java Reference
In-Depth Information
public static void printMessage(PhantomReference<BigObject> pr, String msg){
System.out.println(msg);
System.out.println("pr.isEnqueued = " + pr.isEnqueued());
System.out.println("pr.get() = " + pr.get());
// We will check if pr is queued. If it has been queued,
// we will clear its referent's reference
if (pr.isEnqueued() ) {
pr.clear();
System.out.println("Cleared the referent's reference");
}
System.out.println("-----------------------");
}
}
Invoking gc() first time:
pr.isEnqueued = false
pr.get() = null
-----------------------
After invoking gc() first time:
pr.isEnqueued = false
pr.get() = null
-----------------------
finalize() called for id:1857
Invoking gc() second time:
pr.isEnqueued = false
pr.get() = null
-----------------------
After invoking gc() second time:
pr.isEnqueued = true
pr.get() = null
Cleared the referent's reference
-----------------------
You can also use phantom references to coordinate the post-finalization processing of more than one object.
For example, suppose you have three objects called obj1 , obj2 , and obj3 . All of them share a network connection.
When all three objects become unreachable, you would like to close the shared network connection. You can achieve
this by wrapping the three objects in a phantom reference object and using a reference queue. Your program can
wait on a separate thread for all three phantom reference objects to be queued. When the last phantom reference is
queued, you can close the shared network connection. Post-finalization coordination using a phantom reference is
demonstrated in Listing 11-11. Note that the startThread() method of the PhantomRefDemo class uses a thread object
and an anonymous class. The remove() method blocks until there is a phantom reference in the queue. You may get a
different output when you run this program.
Listing 11-11. Post-finalization Coordination Using Phantom References
// PhantomRefDemo.java
package com.jdojo.gc;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
 
Search WWH ::




Custom Search