Sunday, July 29, 2007

Reference queue

The garbage collector puts Reference objects in the ReferenceQueue after their referents have been reclaimed (Phantom references are an exception, because they continue to retain a link to their referents even after they are placed on teh ReferenceQueue).

In most cases when Soft and Weak references are used, we do not care to monitor the ReferenceQueue. However, in case of PhantomReferences, we do want to monitor the ReferenceQueue, because they are used when we wish to do some cleanup activities when the reference is reclaimed. In such cases, a thread which monitors the ReferenceQueue to find out which objects have been reclaimed will be effective. The WeakHashMap class in the JDK however, follows a slightly different strategy as explained here.

While Soft and Weak references can be created without being associated with a ReferenceQueue, Phantom references must always be associated with a ReferenceQueue.

The java.lang.ref.ReferenceQueue class gives us three methods to interact with it:

  • poll – Lets us poll the ReferenceQueue to find out if a reference object has been inserted in it.

  • remove – Returns the next object inserted in the reference queue. This is a blocking call, which means that if an object is not available, the method waits until one becomes available.

  • remove(timeout) – Similar to remove, but if an object is not available, it will block only till the timeout. If a reference object is not available to return, them it returns null.

Note: This text was originally posted on my earlier blog at

No comments: