You cannot do this in Java. All the answers that mention finalizers are not really what you need.
The best you can do is insert a PhantomReference into the ReferenceQueue and poll until you get the link.
final ReferenceQueue rq = new ReferenceQueue(); final PhantomReference phantom = new PhantomReference( referenceToObjectYouWantToTrack, rq );
You want to read Peter Kofler's answer here (he explains what PhantomReference is):
Have you ever used the Phantom link in any project?
It is very interesting to read here:
http://www.kdgregory.com/index.php?page=java.refobj
Basically, I use PhantomReference in a project where I need to calculate a very special type of cache when the software is installed. To efficiently compute this (disk-based) cache, a huge amount of memory is required (the better, the better). I use PhantomReference to track "almost exactly" when this gigantic amount of memory is freed.
NoozNooz42
source share