...
- It is also imprudent to use finalizers for reclaiming scarce resources by inviting garbage collection. Garbage collection usually depends on memory related traits and not on the scarcity of a particular resource. ThusAs a result, if memory is available aplenty, there is no reason for the scarce resource to not get exhausted despite the use of a finalizer. See FIO32-J. Ensure all resources are properly closed when they are no longer needed and CON02-J. Facilitate thread reuse by using Thread Pools for more on handling resources correctly.
...
The SubClass
overrides the protected finalize
method and performs cleanup. Subsequently, it calls super.finalize()
to make sure its superclass is also finalized. The unsuspecting BaseClass
calls the doLogic()
method which happens to be overridden in the SubClass
. This resurrects a reference to SubClass
such that it is not only prevented from getting garbage collected but also cannot use its finalizer anymore in order to close new resources that may have been allocated by the called method. As detailed in MET32-J. Ensure that constructors do not call overridable methods, if the subclass's finalizer has terminated key resources, invoking its methods from the superclass might lead one to observe the object in an inconsistent state and in the worst case result in the infamous NullPointerException
.
...