I have a PR, an object O to which the PR points, and an RQ set up for PR. I have a thread which keeps on polling the RQ, and at the first reference it finds in RQ, the thread prints the time at which it found it, and exits.
Things work fine, but the moment O has a finalize (no matter how trivial), the thread no longer finds a reference in RQ and keeps running indefinitely.
Question: why does it happen this way? I'm using Sun JDK 1.6.
Here's the code:
good case
public class MyGCPhantom
{
public static void main(String[] args) throws InterruptedException
{
GCPhantomObject p = new GCPhantomObject();
ReferenceQueue phantomQueue = new ReferenceQueue();
PhantomReference<GCPhantomObject> pr = new PhantomReference<GCPhantomObject>(p, phantomQueue);
new GCPhantomThread(phantomQueue, "Phantom").start();
p = null;
System.gc();
}
}
class GCPhantomObject
{
@Override
protected void finalize()
{
//System.out.println("GCPhantom finalized " + System.currentTimeMillis());
}
}
class GCPhantomThread extends Thread
{
private ReferenceQueue referenceQueue;
private String name;
GCPhantomThread(ReferenceQueue referenceQueue, String name)
{
this.referenceQueue = referenceQueue;
this.name = name;
}
@Override
public void run()
{
while(referenceQueue.poll() == null);
System.out.println(name + " found at " + System.currentTimeMillis());
}
}
bad case
Just uncomment the SOP in finalize()
of GCPhantomObject
.