javagarbage-collectionphantom-reference

Example of using PhantomReference


As far as I know reference fall into QueueReference when an object that was pointed by the reference gets deleted.

Here an example where I was about to demonstrate this, but it doesn't work. The code inside if has never been executed. What does it mean. Have I used it incorrectly? Or GarbageCollectordidn't work during execution?

public static void main (String[] arg) throws InterruptedException {
        List<String> names = Arrays.asList("Adam", "Eva");
        ReferenceQueue<List<String>> q = new ReferenceQueue<>();
        PhantomReference<List<String>> phantom = new PhantomReference<>(names, q);
        names = null;
        while(true){ 
           PhantomReference ref2 = (PhantomReference)q.poll();
           if(ref2 != null)
               System.out.println(ref2.enqueue());
           Thread.sleep(1000);
        }
    }

Solution

  • PhanomReference will be cleared when GC runs, try System.gc() :

        while (true) {
            System.gc();