Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tweaked NCE

...

Code Block
bgColor#FFcccc
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(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!
null

Compliant Solution

This solution eliminates the call to the overridable doLogic() method from within the finalize() method.

...