Versions Compared

Key

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

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 are released as resource management does not happen automatically while reclaiming when memory is reclaimed. In Java, the finalize() method of java.lang.Object is used for this purpose.

...

  • There is no fixed time for finalizers to get executed; this detail is JVM dependent: The only thing that is guaranteed is that if 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. No time-critical functionality should be implemented 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 termination is also not guaranteed to work. Methods such as System.gc(), System.runFinalization(), System.runFinalizersOnExit() and Runtime.runFinalizersOnExit() are either just marginally better or have been deprecated because of lack of safety and deadlock causing effects.

...

  • Effect of uncaught exceptions: An uncaught exception thrown during finalization is ignored. The finalization process itself stops immediately so it fails to accomplish its sole purpose.
  • Coding errors that result in memory leaks can also cause finalizers to never execute to completion.
  • A programmer may unintentionally resurrect 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 Superclasses that use finalizers and pass some bring additional overhead burden to their extending classes. An Consider 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 its inherited finalize() method gets called, and lasts persists for at least two garbage collection cycles.

...

...

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

Noncompliant Code Example

The This noncompliant example uses 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 MET36-J. Do not use deprecated or obsolete methods).

...

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 being garbage collected but also cannot further use from using 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.

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();  // callCall 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();
      // artificiallyArtificially simulate finalization (do not do this)
      System.runFinalizersOnExit(true); 
    } catch (Throwable t) { 
      //* handleHandle error 
   */ }  		
  }
}

This code outputs:

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

...

Code Block
bgColor#ccccff
class BaseClass {
  protected void finalize() throws Throwable {
    System.out.println("superclass finalize!");
    // eliminateEliminate the call to the overridden doLogic().
  }
  ...
}

...

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.

...

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
Class MyFrame {
  private JFrame frame; 
  private byte[] buffer = new byte[16 * 1024 * 1024]; // now decoupled
}

Risk Assessment

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

...