...
Code Block | ||
---|---|---|
| ||
class BaseClass { protected void finalize() throws Throwable { System.out.println("Superclass finalize!"); doLogic(); } public void doLogic() throws Throwable{ System.out.println("This is super-class!"); } } class SubClass extends BaseClass { private Date d; // mutable instance field protected SubClass() { d = new Date(); } protected void finalize() throws Throwable { System.out.println("Subclass finalize!"); try { // cleanup resources d = null; } finally { super.finalize(); // call BaseClass' finalizer } } public void doLogic() throws Throwable{ System.out.println("This is sub-class!"); /* any resource allocations made here will persist */ // inconsistent object state System.out.println("This is sub-class! The date object is: " + d); // 'd' is already null } } public class BadUse { public static void main(String[] args) { try { BaseClass bc = new SubClass(); System.runFinalizersOnExit(true); // artificially simulate finalization (do not do this) } catch (Throwable t) { /* handle error */ } } } |
...
Code Block |
---|
Subclass finalize! Superclass finalize! This is sub-class! The date object is: null |
Compliant Solution
This solution eliminates the call to the overridable doLogic()
method from within the finalize()
method.
...