...
- Garbage collection usually depends on memory availability and usage rather than on the scarcity of some other particular resource. Consequently, when memory is readily available, a scarce resource may be exhausted in spite of the presence of a finalizer that could release the scarce resource if it were executed. See guidelines rules FIO06-J. Ensure all resources are properly closed when they are no longer needed and TPS00-J. Use thread pools to enable graceful degradation of service during traffic bursts for more details on handling scarce resources correctly.
...
This noncompliant code example uses the System.runFinalizersOnExit()
method to simulate a garbage collection run. Note that this method is deprecated because of thread-safety issues; see guideline rule MET15-J. Do not use deprecated or obsolete classes or methods.
...
The class SubClass
overrides the protected
finalize
method and performs cleanup activities. 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 being garbage collected but also from using its finalizer to close new resources that may have been allocated by the called method. As detailed in guideline rule MET04-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. In some cases this can result in the infamous NullPointerException
.
...
Wiki Markup |
---|
Joshua Bloch \[[Bloch 2008|AA. Bibliography#Bloch 08]\] suggests implementing a {{stop()}} method explicitly such that it leaves the class in an unusable state beyond its lifetime. A {{private}} field within the class can signal whether the class is unusable. All the class methods must check this field prior to operating on the class. This is akin to [the first exception|OBJ05-J. Prevent access to partially initialized objects#OBJ04-EX1] discussed in guidelinerule [OBJ05-J. Prevent access to partially initialized objects]. As always, a good place to call the termination logic is in the {{finally}} block. |
...