Edit:
As NoozNooz42 has pointed out, a PhantomReference
can do everything a finalizer can, without the problems finalizers present. So, I encourage using PhantomReferences
over extending finalize()
. I am keeping my original post in tact, since I think Java programmers should at least know that finalize()
exists.
Original Post:
Every Java class has a finalize()
method that gets run when no other Objects hold a reference to that class. You can extend this method like so:
protected void finalize() throws Throwable {
try {
// Do whatever you want
} finally {
super.finalize();
}
}
By doing so, you can figure out if anything holds a reference to the Objects in question. Just make sure you always call super.finalize()
if you use this approach.
Reference on finalization:
http://java.sun.com/developer/technicalArticles/javase/finalization/