clear()
simply sets the internal reference to null
. Since references are automatically cleared when being enqueued by the garbage collector (with the exception of phantom references, but this oddity can be ignored, it will be eliminated in Java 9), there is usually no need to call clear()
on a reference received via ReferenceQueue.remove()
.
In principle, there is the possibility to enqueue references manually via enqueue()
without clearing them, but there is little sense in that, as the primary purpose of the reference queue is to learn about references being enqueued by the garbage collector which will be cleared.
When you call clear()
on a Reference
object that has not been enqueued yet, it may allow the referent to get collected without enqueuing the Reference
object. On the other hand, when you don’t need the Reference
object anymore, you can let the JVM collect it like an ordinary object, together with the referent if there are no other references left, as in that case, it won’t get enqueued as well, making clear()
unnecessary.