ReferenceQueue q = new ReferenceQueue();
Reference r = q.remove();
r.clear();
I see that the java doc says that the clear
method clears this reference object. I don't understand the meaning of this. Does this clear
from the memory and thus in other words the object has been garbage collected?
java.lang.Reference
is a base class for few special references which are treated in special way by garbage collection.Under certain circumstances garbage collector may push reference object in it's reference queue (reference may be queued only once in a lifetime).
clear()
method can be used to suppress special handling (and thus additional work for garbage collector). If reference object is already in queue it doesn't make sense to clear it, it is already cleared by garbage collector.This project on github has an implementation of resource management using
PhantomReference
s made for educational purpose.clear()
is used if resource is disposed explicitly to avoid extra work for GC in that case.