Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sonarqube

I am getting SonarQube error that : "Calling the super.finalize() at the end of this method implementation is highly recommended in case parent implementations must also dispose some system resources."

But I found that Object class has no implementation for finalize method.

protected void finalize() throws Throwable { }

So why need to call super.finalize()?

like image 605
2787184 Avatar asked Aug 13 '15 10:08

2787184


2 Answers

It's not a need, it's a finalizer writing idiom that should be followed.

If, at any time in the future, you refactor your code and your class extends some other class that may have a finalize method, this practice will prevent strange bugs from popping up.

The idiom is

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

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

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

like image 98
RealSkeptic Avatar answered Oct 19 '22 10:10

RealSkeptic


The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

Who knows, super class of your current class ovveriden this method.

Look where you are in the below hierarchy.

Object  --- no implementation 

  -- 

    -- Your Super class -- Overriden the finalize 

      -- Current class

Super doesn't always represent the Object class. There might be no of super classes in middle.

like image 45
Suresh Atta Avatar answered Oct 19 '22 10:10

Suresh Atta