You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 33 Next »

Before the garbage collector acts on an object to reclaim it, the object's finalizer is executed. This is required to ensure that resources such as open streams, files and network connections get released as resource management does not happen automatically while reclaiming memory. In Java, the finalize() method of java.lang.Object is used to perform this activity.

The caveats associated with the use of finalizers are discussed here:

  • There is no fixed time for finalizers to get executed; this detail is JVM dependent: The only thing that is guaranteed is that if at all a finalizer gets executed, it will be before the garbage collector's second cycle. An object may become unreachable and yet its finalizer may not execute for an arbitrarily long time. Nothing of time-critical nature should be run in the finalize method. For instance, closing file handles is not recommended.
  • Do not depend on a finalizer for updating critical persistent state: It is possible for the JVM to terminate without invoking the finalizer on an unreachable object. Finalization on process exit is also not guaranteed. Methods such as System.gc, System.runFinalization, System.runFinalizersOnExit and Runtime.runFinalizersOnExit are either just marginally better or have been deprecated due to lack of safety and deadlock causing effects.
  • According to the Java Language Specification: [[JLS 05]] Section 12.6.2 "Finalizer Invocations are Not Ordered":

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

    This can be a problem as slow running finalizers tend to block others in the queue.
  • Effect of uncaught exceptions: An uncaught exception thrown during finalization is ignored. The finalization process itself stops immediately so it fails to accomplish its purpose.
  • Unintentional mistakes like memory leaks can also cause finalizers to never execute to completion.
  • A possibility exists such that the programmer unintentionally resurrects the object's reference in the finalize method. While the garbage collector must determine yet again whether the object is free to be deallocated, the finalize method is not invoked again.
  • A superclass can use finalizers and pass some additional overhead to extending classes. An example from JDK 1.5 and earlier demonstrates this. The code snippet shown below allocates a 16 MB buffer for backing a Swing Jframe. None of the JFrame APIs have a finalize method, however, JFrame extends AWT Frame which has a finalize method. The byte buffer continues to persist until the finalize method gets called and lasts for at least two garbage collection cycles.
Class MyFrame extends Jframe {
  private byte[] buffer = new byte[16 * 1024 * 1024]; // persists for at least two GC cycles 
}
  • A common myth is that finalizers aid garbage collection. On the contrary, they increase garbage collection time and introduce space overheads. They also fail to respect the modern generational garbage collectors. Another trap unfolds while trying to finalize reachable objects, an exercise that is always counterproductive.
  • It is not advisable to use any lock or sharing based mechanisms within a finalizer due to the inherent dangers of deadlock and starvation. On the other hand, it is also easy to miss that there can be synchronization issues with the use of finalizers even if the source program is single-threaded. This is because the finalize() methods are called from their own threads. If at all finalizer is necessary, the cleanup data structure should be protected from concurrent access (See [[Boehm 05]]).

Noncompliant Code Example

The System.runFinalizersOnExit() method is used in this noncompliant example to simulate a garbage collection run (note that this method is deprecated because of thread-safety issues).

According to the Java API [[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 getting garbage collected but also cannot further use its finalizer to close new resources that may have been allocated by the called method. As detailed in MET32-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' 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 */ }  		
  }
}

As expected, this code outputs:

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.

class BaseClass {
  protected void finalize() throws Throwable {
    System.out.println("superclass finalize!");
    // eliminate the call to the overridden doLogic().
  }
  ...
}

Exceptions

OBJ02-EX1: Sometimes it is necessary to use finalizers especially while working with native objects/code. This is because the garbage collector cannot re-claim memory used by code written in another language. Also, the lifetime of the object is often unknown. Again, the native process must not perform any critical jobs that require immediate resource deallocation.

In such cases, finalize should be used correctly. 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 05]] Section 12.6.1: Implementing Finalization.

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 is reachable before A's finalizer has concluded. This can be achieved by adding a reference to B in some global state variable and removing it as soon as A's finalizer gets executed. An alternative is to use the java.lang.ref references.

If a superclass defines a finalize method, make sure to decouple the objects that can be immediately garbage collected from those that depend on the finalizer. In the MyFrame example, the following code ensures that the buffer doesn't persist longer than expected.

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

Compliant Solution (finalization)

Joshua Bloch [[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 EX1 discussed in [OBJ32-J. Do not allow partially initialized objects to be accessed]. As always, a good place to call the termination logic is in the finally block.

Risk Assessment

The 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

OBJ02- J

medium

probable

medium

P8

L2

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[JLS 05]] Section 12.6, Finalization of Class Instances
[[API 06]] finalize()
[[Bloch 08]] Item 7, Avoid finalizers
[[Darwin 04]] Section 9.5, The Finalize Method
[[Flanagan 05]] Section 3.3, Destroying and Finalizing Objects
[[Coomes 07]] "Sneaky" Memory Retention
[[Boehm 05]]
[[MITRE 09]] CWE ID 586 "Explicit Call to Finalize()", CWE ID 583 "finalize() Method Declared Public", CWE ID 568 "finalize() Method Without super.finalize()"


OBJ01-J. Understand how a superclass can affect a subclass      07. Object Orientation (OBJ)      OBJ03-J. Be aware that a final reference may not always refer to immutable data

  • No labels