Versions Compared

Key

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

...

  • 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 because of lack of safety and deadlock causing effects.
  • Wiki Markup
    According to the Java Language Specification: \[[JLS 05|AA. Java References#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.

    This can be a problem as slow running finalizers tend to block others in the queue.

...

  • Wiki Markup
    It is not advisable to use any lock or sharing based mechanisms within a finalizer duebecause toof 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 a finalizer is necessary, the cleanup data structure should be protected from concurrent access (See \[[Boehm 05|AA. Java References#Boehm 05]\]).

...

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{
    /* 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 This code outputs:

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

Compliant Solution

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

Code Block
bgColor#ccccff
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.

Code Block

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

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 05|AA. Java References#JLS 05]\] Section 12.6.1: Implementing Finalization.

Code Block

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.

Code Block

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

Compliant Solution (finalization)

...

Compliant Solution (finalization)

Wiki Markup
Joshua Bloch \[[Bloch 08|AA. Java References#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.

Exceptions

OBJ02-EX1: Sometimes it is necessary to use finalizers especially when working with native 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.

Code Block

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

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 05|AA. Java References#JLS 05]\] 

Code Block

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.

Code Block

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

...

Risk Assessment

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

...