Understand ReferenceQueue

All Reference types can be constructed with ReferenceQueue. The queue servers as a registry to let user poll to recognize the garbage collected referent. In general, user starts a daemon thread to poll from the queue to get notified.

The queue internal is a linked list which has a head to visit the list. List node is the Reference. A queue can be shared, so its methods - remove, poll and enqueue are all synchronized by the inner lock object.

  1. Ref stays active if the wrapped referent is active in usage and cannot be garbage collected.
  2. Ref has no any strong ref will be put to pending list by GC. Status turns to pending.
  3. ReferenceHandler is a daemon thread which fetches Ref from pending list to ref’s queue. Ref is then in Enqueued status.
  4. User thread will poll element from the reference queue to get notified.

Notice that ReferenceHandler is a daemon thread that is started along with JVM. So is the Finalizer. Finalizer is another daemon thread that executes object’s finalize method before GC. But it has lower priority than ReferenceHandler.