The garbage collector invokes object finalizer methods after it has determined that the object is unreachable but before it reclaims the object's storage. Execution of the finalizer provides an opportunity to release resources such as open streams, files, and network connections that might not otherwise be released automatically through the normal action of the garbage collector.

There are a sufficient number of problems associated with finalizers to restrict their use to exceptional conditions:

Because of these problems, finalizers must not be used in new classes.

Noncompliant Code Example (Superclass finalizer())

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 none of the JFrame APIs have a finalize() method, 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.

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

Compliant Solution (Superclass finalizer())

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.

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

Noncompliant Code Example (System.runFinalizersOnExit())

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 MET02-J. Do not use deprecated or obsolete classes or methods.

According to the Java API \[[API 2006|AA. Bibliography#API 06]\] class {{System}}, {{runFinalizersOnExit()}} method documentation,

Enable or disable finalization on exit; doing so specifies that the finalizers of all objects that have finalizers that have not yet been automatically invoked are to be run before the Java runtime exits. By default, finalization on exit is disabled.

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 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 lead one to observe the object in an inconsistent state. In some cases this can result in the infamous NullPointerException.

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:

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

Compliant Solution

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|OBJ11-J. Prevent access to partially initialized objects#OBJ04-EX1] discussed in rule [OBJ11-J. Prevent access to partially initialized objects|OBJ11-J. Prevent access to partially initialized objects]. As always, a good place to call the termination logic is in the {{finally}} block.

Exceptions

MET12-EX0: Finalizers may be used when working with native code because the garbage collector cannot reclaim memory used by code written in another language and because the lifetime of the object is often unknown. Again, the native process must not perform any critical jobs that require immediate resource deallocation.

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.

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

Alternatively, 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 non-final 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|AA. Bibliography#JLS 05]\].

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
    }
  };
  //...
}

The ordering problem can be dangerous when dealing with native code. For example, if object A references object B (either directly or reflectively) and the latter gets finalized first, A's finalizer may end up dereferencing dangling native pointers. To impose an explicit ordering on finalizers, make sure that B remains reachable until A's finalizer has concluded. This can be achieved by adding a reference to B in some global state variable and removing it when A's finalizer executes. An alternative is to use the java.lang.ref references.

Risk Assessment

Improper use of finalizers can result in resurrection of garbage-collection ready objects and result in denial-of-service vulnerabilities.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET12-J

medium

probable

medium

P8

L2

Related Vulnerabilities

AXIS2-4163

Related Guidelines

MITRE CWE

CWE-586, "Explicit Call to Finalize()"

 

CWE-583, "finalize() Method Declared Public"

 

CWE-568, "finalize() Method Without super.finalize()"

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8b8bb6b6-3cb2-46e4-9f70-34c1e9a8c80f"><ac:plain-text-body><![CDATA[

[[API 2006

AA. Bibliography#API 06]]

[finalize()

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize()]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c39acdbe-6156-404f-8ce9-107d2018929f"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 7, Avoid finalizers

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d029437a-6653-43a0-84a1-370db28e605d"><ac:plain-text-body><![CDATA[

[[Boehm 2005

AA. Bibliography#Boehm 05]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9f694d7c-891a-4805-8868-a18bc05b8b71"><ac:plain-text-body><![CDATA[

[[Coomes 2007

AA. Bibliography#Coomes 07]]

"Sneaky" Memory Retention

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2afea7fb-eddc-419a-a9a8-54fd8334efd5"><ac:plain-text-body><![CDATA[

[[Darwin 2004

AA. Bibliography#Darwin 04]]

Section 9.5, The Finalize Method

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a30c0475-7744-40fe-ab52-7650451f3d93"><ac:plain-text-body><![CDATA[

[[Flanagan 2005

AA. Bibliography#Flanagan 05]]

Section 3.3, Destroying and Finalizing Objects

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a3cd7c17-014d-4c52-a2a9-1e84629a0595"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

Section 12.6, Finalization of Class Instances

]]></ac:plain-text-body></ac:structured-macro>


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