Assume that I have the following class
class A {
//some attributes
@override
protected void finalize() throws Throwable {
//do something
}
}
class B extends A {
@override
protected void finalize() throws Throwable {
//DONT call super.finalize()
//do something
}
}
What will happen in this scenario ? Will calling class A' finalize method will be called by garbage collector at some point?
What is the different between calling it and not calling A's finalize method in the child class' finalize method if it's anyway going to be called by garbage collector ?
In what scenario, it is ok NOT to call its parent's finalize method in the child class? Any example of such a scenario ?
First off, explicitly calling a finalize() method is just like calling any other Java method. It is never OK to not call the parent's finalize() method if your specific class is overriding the finalize()
method. Of course, if you implement the finalizer guardian pattern, you don't need to explicitly call the parent finalizer in your subclass.
BTW, don't rely on finalize()
methods for cleaning up resources which can be cleared explicitly (like closing file handles etc.) since finalizers are non-deterministic. Also, take a look at the presentation by Bob Lee for using Phantom references in place of finalizers.