Example of ReferenceQueue in Java
January 03, 2013
ReferenceQueue belongs to the package java.lang.ref. Garbage collector appends the object’s reference in ReferenceQueue. ReferenceQueue has the methods poll , remove . poll method fetches the reference object to check its availability. remove method removes the reference object from ReferenceQueue and and it waits until one object reference becomes available in ReferenceQueue. ReferenceQueue is used with PhantomRefernce, WeakReference etc.
package com.concretepage; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; public class ReferenceQueueTest { public static void main(String... args){ ReferenceQueuerq= new ReferenceQueue (); String s="hello"; Reference r= new PhantomReference (s,rq); s=null; System.gc(); System.out.println(rq.poll()); } }