Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you call super.finalize() within a subclass?

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()?

like image 487
user997112 Avatar asked Jul 07 '12 22:07

user997112


2 Answers

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.

like image 155
Jeff Storey Avatar answered Sep 27 '22 17:09

Jeff Storey


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).

like image 24
ali haider Avatar answered Sep 27 '22 17:09

ali haider