Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

...

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.

...