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?
Not sure if this really answers your question, but the finalize() method of an object is called prior to its resources being reclaimed.
Edit: Which means that you can send a message to another object to alert it, or something along those lines.
According to the source code, it uses the PhantomReference class. According to the documentation:
The
PhantomReference
constructor accepts two arguments:The
q
argument is an instance of theReferenceQueue
class. ThePhantomReference
will be added to thisReferenceQueue
when it'sreferent
becomes phantom reachable. When this happens, you can retrieve thePhantomReference
by using thepoll()
orremove()
methods of theReferenceQueue
class.For example:
Note:
PhantomReference
has sibling classes namedSoftReference
andWeakReference
that may also be of use. The relationship between these are documented in the java.lang.ref package documentation.