Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is phantom reference not queued?

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.

like image 729
Tony Hu Avatar asked Jan 28 '26 10:01

Tony Hu


1 Answers

The garbage collector treats a reference object like any other object. From the documentation:

If a registered reference becomes unreachable itself, then it will never be enqueued.

In theory, yes, using reference objects will introduce inefficiency to garbage collection, so I would not create a reference object for every application object. But in practice the set of reference objects tends to be very small: they're intended to track resources like database connections, not arbitrary objects.

like image 120
guest Avatar answered Jan 30 '26 00:01

guest