I am leaning phantom reference ,and I got confused how is a phantom reference enqueued when the referent is being garbage-collected.
Here is my code
Object s = new Object();
ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
PhantomReference<Object> ref = new PhantomReference<Object>(s, queue);
s = null;
System.gc();
TimeUnit.SECONDS.sleep(1);
System.out.println(queue.poll());
As expected, queue.poll will return the phantom reference :ref.
But if I make a little change of the code : remove the local variable "ref", queue.poll will return null.
So I can infer that, when JVM tries to garbage collect an object ,it will check all the reference to see if there was any that can reach the object.
This should be a very slow progress.?
I designed a program: use phantom reference to trace resource leak. When resource is allocated, a phantom reference is new and bind to the resource.Then I found that:all the phantom references must be stored ,otherwise the phantom reference will not enqueue.
And I checked the netty code ,found that ,netty stores all the phantom references :io.netty.util.ResourceLeakDetector#allLeaks.