Versions Compared

Key

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

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 is no fixed time at which finalizers must be executed as because this depends on the JVM. The only guarantee is that any finalizer method that executes will do so sometime after the associated object has become unreachable (detected during the first cycle of garbage collection) , and sometime before the garbage collector reclaims the associated object's storage (during the garbage collector's second cycle). Execution of an object's finalizer may be delayed for an arbitrarily long time after the object becomes unreachable. Consequently, invoking time-critical functionality such as closing file handles in a finalizer in an object's finalize() method is problematic.
  • The JVM may terminate without invoking the finalizer on some or all unreachable objects. Consequently, attempts to update critical persistent state from finalizer methods can fail without warning. Similarly, Java provides no guarantee that finalizers will execute on process termination. Methods such as System.gc(), System.runFinalization(), System.runFinalizersOnExit(), and Runtime.runFinalizersOnExit() either lack such guarantees or have been deprecated because of lack of safety and potential for deadlock.
  • Wiki Markup
    According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 12.6.2, "Finalizer Invocations are Not Ordered,"

    Wiki Markup
    The Java programming language imposes no ordering on {{finalize}} method calls. Finalizers \[of different objects\] may be called in any order, or even concurrently.

    One consequence is that slow-running finalizers can delay execution of other finalizers in the queue. Further, the lack of guaranteed ordering can lead to substantial difficulty in maintaining desired program invariants.

...

  • Coding errors that result in memory leaks imply that objects incorrectly remain reachable; consequently, their finalizers are never invoked.

...

...

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.

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

Compliant Solution (Superclass finalizer())

...

Code Block
bgColor#ccccff
Class MyFrame {
  private JFrame frame; 
  private byte[] buffer = new byte[16 * 1024 * 1024]; // now decoupled
}

...

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

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

...

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|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.

...

Wiki Markup
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]\] .

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

...

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

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="241b22a78f3217bd-0d6fb8ae-4b664384-8e0c8264-90e1e18b49a09d6f379c6f63"><ac:plain-text-body><![CDATA[

[[MITRE 2009

AA. Bibliography#MITRE 09]]

[CWE ID -586

http://cwe.mitre.org/data/definitions/586.html] "Explicit Call to Finalize()" , and [CWE ID -583

http://cwe.mitre.org/data/definitions/583.html] "finalize() Method Declared Public"

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

 

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

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c1419f5dea7dbb4d-7a24208b-4b9344d0-9c249acb-f4e2f2635b8eb9e2013eddc1"><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="5f4b34a513db7432-c27e20af-400c47a6-b709b9a1-3d6443f756b4e3adb5feb70e"><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="b9f314fa9e3128f7-e4a0556d-4ece4dcb-8b3ead6f-4967004f830bbee39c8525c1"><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="8bd5105f0dffebc5-ee5bca23-4d71452d-aea78177-4548ae36d62a817d3dc35642"><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="3e70b185a1546812-3c58af63-4dc64042-abe8b1b9-bf828e7b3c183018409d2a1b"><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="892dd7102a6b52dd-7d8369a0-431b4712-9da18bc0-77482cbd1679e4f1e16bdbd7"><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="e581b3c55c765bf2-5a3ea1e1-4b9a46da-9545b10f-aaca6b890d8a9de21e182731"><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>

...