Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: grouped MyFrame code samples together

...

  • Superclasses that use finalizers impose additional constraints on their extending classes. Consider an example from JDK 1.5 and earlier. The code snippet below 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 
}
  • It is a common myth that finalizers aid garbage collection. On the contrary, they increase garbage collection time and introduce space overheads. Finalizers interfere with the operation of modern generational garbage collectors by extending the lifetimes of many objects. Incorrectly programmed finalizers could also attempt to finalize reachable objects, which is always counterproductive and can violate program invariants.
  • Wiki Markup
    Use of finalizers can introduce synchronization issues even when the remainder of the program is single-threaded. The {{finalize()}} methods are invoked by the garbage collector from one or more threads of its choice; these threads are typically distinct from the {{main()}} thread, although this property is not guaranteed. When a finalizer is necessary, any required cleanup data structures should be protected from concurrent access. See \[[Boehm 2005|AA. Bibliography#Boehm 05]\] for additional information.
  • Use of locks or other synchronization-based mechanisms within a finalizer can cause deadlock or starvation. This possibility arises because both the invocation order and the executing thread or threads for finalizers cannot be guaranteed or controlled.

Noncompliant Code Example

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 guideline MET15-J. Do not use deprecated or obsolete 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 guideline MET04-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.

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. In the MyFrame example, the following code 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
}
  • It is a common myth that finalizers aid garbage collection. On the contrary, they increase garbage collection time and introduce space overheads. Finalizers interfere with the operation of modern generational garbage collectors by extending the lifetimes of many objects. Incorrectly programmed finalizers could also attempt to finalize reachable objects, which is always counterproductive and can violate program invariants.
  • Wiki Markup
    Use of finalizers can introduce synchronization issues even when the remainder of the program is single-threaded. The {{finalize()}} methods are invoked by the garbage collector from one or more threads of its choice; these threads are typically distinct from the {{main()}} thread, although this property is not guaranteed. When a finalizer is necessary, any required cleanup data structures should be protected from concurrent access. See \[[Boehm 2005|AA. Bibliography#Boehm 05]\] for additional information.
  • Use of locks or other synchronization-based mechanisms within a finalizer can cause deadlock or starvation. This possibility arises because both the invocation order and the executing thread or threads for finalizers cannot be guaranteed or controlled.

Noncompliant Code Example

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 guideline MET15-J. Do not use deprecated or obsolete 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 guideline MET04-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
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();
  }

  protectedpublic void finalizedoLogic() throws Throwable {
    System.out.println("Subclass finalizeThis is super-class!");
  }
}

class SubClass extends tryBaseClass {
  private Date  d; // mutable instance cleanupfield

 resources 
protected SubClass() {
    d = new null;				Date();
    } finally {}

  protected  void  super.finalize(); throws // Call BaseClass's finalizerThrowable {
    }
  }
	
  public void doLogic() throws ThrowableSystem.out.println("Subclass finalize!");
    try {
      // any resource allocations made here will persist 
  cleanup resources 
      d = null;				
    //} inconsistentfinally object{
 state
    System.out.println("This is sub-class! The date object is: " + d super.finalize();  // Call BaseClass'd's isfinalizer
 already null
  }
  }
	
  public class BadUse void doLogic() throws Throwable {
  public static void main(String[] args) {
    try {// any resource allocations made here will persist 

    // inconsistent object BaseClassstate
 bc = new SubClass();
      // Artificially simulate finalization (do not do this)
      System.runFinalizersOnExit(true); 
    } catch (Throwable t) { 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 {
 // Handle error 
  BaseClass bc }=  		new SubClass();
  }
}

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().
  }
  ...
}

Compliant Solution (Finalization)

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 *OBJ04-EX1* discussed in guideline [OBJ04-J. Do not allow access to partially initialized objects]. 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() may be used. 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.

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

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().
  }
  ...
}

Compliant Solution (Finalization)

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 *OBJ04-EX1* discussed in guideline [OBJ04-J. Do not allow access to partially initialized objects]. 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() may be used. 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.
Code Block
bgColor#ccccff

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 2005|AA. Bibliography#JLS 05]\] 

...

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.

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. In the MyFrame example, the following code ensures that the buffer can be reclaimed as soon as the object becomes unreachable.

...

bgColor#ccccff

...

Risk Assessment

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

...