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

I read (somewhere) that finalize() for a parent class cannot be called when a subclass collects garbage, does this mean that most developers override finalize() in a subclass and call super.finalize() ?

+7
source share
2 answers

Finalize is not automatically called for the superclass. So if you redefine finalization, the right way to provide a superclass will be cleared

 protected void finalize() { try { // do subclass cleanup } finally { super.finalize(); } } 

See this help article http://www.ibm.com/developerworks/java/library/j-jtp06294/index.html

It is worth noting that finalizers are not very predictable, and you have no control over whether they are executed / when they are executed. Nothing critical should be done in finalization methods. In general, it's best to just do an explicit cleanup of your class.

+13
source

It is better to avoid using finalization to clean up any resources other than Java (call completion is not guaranteed). If possible, use a try with resources (when using JDK7) or finally try suggestions to clear resources, among other parameters, if possible. If you intend to use finalize, you can put super.finalize in a finally try block. It would be wise not to rely on completing the cleanup of resources.

 // don't make it public! protected void finalize() throws Throwable { try { // custom finalization here } finally { super.finalize(); } } 

If the idea is to clear the resources, it would be reasonable, perhaps, to check phantom links - an object is phantom accessible if it is not very / weakly / mildly reachable, it has been completed and there is at least one phantom link (i.e. an object has been completed but not yet restored).

+3
source

All Articles