Why is calling super.finalize () preferable when overriding the finalize () method?

I get a SonarQube error: "Calling super.finalize() at the end of the implementation of this method is highly recommended if the parent implementations must also have some system resources."

But I found that the Object class does not have an implementation for the finalize method.

 protected void finalize() throws Throwable { } 

So why call super.finalize() ?

+7
java sonarqube
source share
3 answers

This is not necessary; it is a finalizer writing down an idiom that must be respected.

If you reorganize your code at any time in the future and your class extends another class that the finalize method may have, this practice will prevent strange errors from occurring.

Idiom

 try { // Do whatever the finalization is } finally { super.finalize(); } 

This ensures that the finalizer of the superclass, if it is ever non-trivial, is called even if some exception is thrown (because nothing catches the exceptions in the finalizers, their execution simply stops).

And of course: Avoid finalizers . (Paragraph 7 in Joshua Bloch Effective Java, second edition).

+6
source share

The finalize method of the Object class takes no special action; he just returns normally. Subclasses of an object may override this definition.

Who knows, the super class of your current class checks this method.

See where you are in the hierarchy below.

 Object --- no implementation -- -- Your Super class -- Overriden the finalize -- Current class 

Super does not always represent the class Object . There may not be superclasses in the middle.

+5
source share

SonarQube error is also explicitly indicated. Note that the class you are writing can have a parent hierarchy at any given time. For effective cleaning, the hierarchy above is always viewed. Regardless of whether you have a superclass, using super.finalize() is thus useful for clearing references from a parent.

+1
source share

All Articles