Java: PhantomReference, ReferenceQueue i finalizacja
Mam PR, obiekt O, który wskazuje PR, i RQ ustawiony na PR. Mam wątek, który kontynuuje odpytywanie RQ, a przy pierwszej znalezionej referencji w RQ wątek wypisuje czas, w którym go znalazł, i wychodzi.
Rzeczy działają dobrze, ale w momencie O ma finalizację (bez względu na to, jak trywialna), wątek nie znajduje już odniesienia w RQ i działa nieprzerwanie.
Pytanie: dlaczego tak się dzieje? Używam Sun JDK 1.6.
Oto kod:
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
Po prostu odkomentuj SPO wfinalize()
zGCPhantomObject
.