Versions Compared

Key

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

...

Superclasses that use finalizers impose additional constraints on their extending classes. Consider an example from JDK 1.5 and earlier. The following noncompliant code example allocates a 16 MB buffer used to back a Swing JFrame object. Although the JFrame APIs lack finalize() methods, JFrame extends AWT.Frame, which does have a finalize() method. When a MyFrame object becomes unreachable, the garbage collector cannot reclaim the storage for the byte buffer because code in the inherited finalize() method might refer to it. Consequently, the byte buffer must persist at least until the inherited finalize() method for class MyFrame completes its execution and cannot be reclaimed until the following garbage-collection cycle.

Code Block
bgColor#ffcccc

class MyFrame extends JFrame {
  private byte[] buffer = new byte[16 * 1024 * 1024];
  // persists for at least two GC cycles
}

...

When a superclass defines a finalize() method, make sure to decouple the objects that can be immediately garbage collected from those that must depend on the finalizer. This compliant solution ensures that the buffer can be reclaimed as soon as the object becomes unreachable.

Code Block
bgColor#ccccff

class MyFrame {
  private JFrame frame;
  private byte[] buffer = new byte[16 * 1024 * 1024]; // now decoupled
}

...

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 that not only prevents it from being garbage-collected but also prevents it from calling its finalizer to close new resources that may have been allocated by the called method. As detailed in rule MET05-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 result in the observation of object in an inconsistent state. In some cases, this can result in NullPointerException.

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's finalizer
    }
  }

  public void doLogic() throws Throwable {
    // 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();
      // Artificially simulate finalization (do not do this)
      System.runFinalizersOnExit(true);
    } catch (Throwable t) {
      // Handle error
    }
  }
}

This code outputs:

Code Block

Subclass finalize!
Superclass finalize!
This is sub-class! The date object is: null

...

Any subclass that overrides finalize() must explicitly invoke the method for its superclass as well. There is no automatic chaining with finalize. The correct way to handle this is shown below.

Code Block
bgColor#ccccff

protected void finalize() throws Throwable {
  try {
    //...
  } finally {
    super.finalize();
  }
}

A more expensive solution is to declare an anonymous class so that the finalize() method is guaranteed to run for the superclass. This solution is applicable to public nonfinal classes. "The finalizer guardian object forces super.finalize to be called if a subclass overrides finalize() and does not explicitly call super.finalize" [JLS 2005].

Code Block
bgColor#ccccff

public class Foo {
  // The finalizeGuardian object finalizes the outer Foo object
  private final Object finalizerGuardian = new Object() {
    protected void finalize() throws Throwable {
      // Finalize outer Foo object
    }
  };
  //...
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET12-J

medium

probable

medium

P8

L2

Automated Detection

Tool
Version
Checker
Description
Coverity7.5

CALL_SUPER

DC.THREADING

FB.FI_EMPTY

FB.FI_EXPLICIT_INVOCATION

FB.FI_FINALIZER_NULLS_FIELDS

FB.FI_FINALIZER_ONLY_NULLS_FIELDS

FB.FI_MISSING_SUPER_CALL

FB.FI_NULLIFY_SUPER

FB.FI_USELESS

FB.FI_PUBLIC_SHOULD_BE_ PROTECTED

Implemented

Related Vulnerabilities

AXIS2-4163 describes a vulnerability in the finalize() method in the Axis web services framework. The finalizer incorrectly calls super.finalize() before doing its own cleanup. This leads to errors in GlassFish when the garbage collector runs.

...

[API 2006]

finalize()

[Bloch 2008]

Item 7. Avoid finalizers

[Boehm 2005]

 

[Coomes 2007]

"Sneaky" Memory Retention

[Darwin 2004]

Section 9.5, The Finalize Method

[Flanagan 2005]

Section 3.3, Destroying and Finalizing Objects

[JLS 2005]

§12.6, Finalization of Class Instances

 

      05. Methods (MET)      06. Exceptional Behavior (ERR)