I was just digging around in the commons-io library and found this:
Keeps track of files awaiting deletion, and deletes them when an associated marker object is reclaimed by the garbage collector.
This can be found in the documentation for the FileCleaningTracker object.
Now I am just curious how I can do this by myself? How can my code detect when an object is reclaimed by the garbage collector?
According to the source code, it uses the PhantomReference class. According to the documentation:
The
PhantomReferenceconstructor accepts two arguments:The
qargument is an instance of theReferenceQueueclass. ThePhantomReferencewill be added to thisReferenceQueuewhen it’sreferentbecomes phantom reachable. When this happens, you can retrieve thePhantomReferenceby using thepoll()orremove()methods of theReferenceQueueclass.For example:
Note:
PhantomReferencehas sibling classes namedSoftReferenceandWeakReferencethat may also be of use. The relationship between these are documented in the java.lang.ref package documentation.