I read (somewhere) that finalize()
for a parent class is not guaranteed to be called when the subclass is garbage-collected, does this mean most developers override finalize()
in the subclass and call super.finalize()
?
Finalize is not automatically called for the super class. So if you override finalize, the proper way to ensure the super class gets cleaned up would be
protected void finalize() {
try {
// do subclass cleanup
}
finally {
super.finalize();
}
}
See this reference article http://www.ibm.com/developerworks/java/library/j-jtp06294/index.html
It should be worth noting that finalizers are not very predictable and you don't have any control over if/when they run. Nothing critical should be done in finalize methods. In general it is better practice to just perform explicit cleanup of your class.
Its best to avoid relying on finalize for cleaning up any non Java resources (finalize calls are not guaranteed). If possible, use try with resources (if using JDK7) or try finally clauses to clean up resources amongst other options where possible. If you are going to use finalize, you can put the super.finalize in a try finally block. It would be wise to not rely on finalize to clean up resources.
// don't make it public!
protected void finalize() throws Throwable
{
try
{
// custom finalization here
}
finally
{
super.finalize();
}
}
If the idea is to clean up resources, it would be wise to perhaps check out phantom references - an object is phantomly reachable if it is neither strongly/weakly/softly reachable, has been finalized & there is at least one phantom reference (i.e object has been finalized but not yet reclaimed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With