4

Could u help me please with understanding PhantomReference? I know that PhantomReference help with tracking when object was removed from heap, and is reachable after finalize method is called. I have tried to get my hands dirty with some code but I cant get it right e.g

 class Foo{

    private String a;
    public Foo(String a){
        this.a = a;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();             
        System.out.println("calling finalize");
    }

    @Override
    public String toString() {
        return "Foo{" + "a=" + a + '}';
    }                                


}

I thought that doing something like this:

    ReferenceQueue q = new ReferenceQueue();                
    PhantomReference<Foo> pr = new PhantomReference(new Foo("myphantom"), q);        

    System.out.println("Object created trying to gc");

    System.gc();        
    Thread.sleep(5000L);                              

    System.out.println(q.poll());

Will give me instance of PhantomReference, but what i got is null.

  • Are you saying the object you attempted to retrieve from the PhantomReference is null? According to the JavaDocs, "The get method of a phantom reference always returns null." – bdkosher Nov 25 '15 at 15:56
  • @bdkosher Yeah I know that, but in this example Im trying to get instance of PhantomReference from RefrenceQueue not a referent of PhantomReference – Krzysztof Szewczyk Nov 25 '15 at 22:37

1 Answers1

1

This is what worked for me.

        ReferenceQueue<Foo> q = new ReferenceQueue<Foo>();
        PhantomReference<Foo> pr = new PhantomReference<Foo>(new Foo("myphantom"), q);
        System.gc();
        System.runFinalization();
        System.gc();
        System.runFinalization();
//      Reference<? extends Foo> remove = q.remove(5000L); 
        System.out.println(q.poll());

I got the answer to your question in here: Java: PhantomReference, ReferenceQueue and finalize

Community
  • 1
  • 1
awsome
  • 2,143
  • 2
  • 23
  • 41