Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

The garbage collector invokes object finalizer methods after it has determined determines 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 are a A sufficient number of problems are associated with finalizers to restrict their use to exceptional conditions:

  • There is no fixed time at which finalizers must be executed as this because time of execution depends on the Java Virtual Machine (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 lacks any 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.unmigrated-wiki-markup
  • According to the The Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\] Section 12.6.2 "Finalizer Invocations are Not Ordered" (JLS), §12.6, "Finalization of Class Instances" [JLS 2015]:

    The Java programming language imposes no ordering on finalize() method calls. Finalizers [of different objects] may be called in any order, or even Wiki MarkupThe 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.
  • Uncaught exceptions thrown during finalization are ignored. When an exception is thrown in a finalizer propagates beyond the finalize() method, the process itself immediately stops , and consequently fails to accomplish its sole purpose. This termination of the finalization process may or may not prevent all subsequent finalization from executing. The JLS fails to define this behavior, leaving it to the individual implementations.
  • Coding errors that result in memory leaks imply that can cause objects to incorrectly remain reachable; consequently, their finalizers are never invoked.

...

  • 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.unmigrated-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 must be protected from concurrent access. See \[See the JavaOne presentation by Hans J. Boehm [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 neither the invocation order and nor the specific executing thread or threads for finalizers cannot can be guaranteed or controlled.

Object finalizers have also been deprecated since Java 9. See MET02-J. Do not use deprecated or obsolete classes or methods for more information.

Because of these problems, finalizers must Because of these problems, finalizers must not be used in new classes.

Noncompliant Code Example (Superclass's finalizer

...

)

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 JFrame object. Although none of the JFrame APIs have a lack finalize() method methods, 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 JframeJFrame {
  private byte[] buffer = new byte[16 * 1024 * 1024];
  // persistsPersists for at least two GC cycles 
}

Compliant Solution (Superclass's finalizer

...

)

...

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. This compliant solution ensures that the buffer can be reclaimed as soon as the object becomes unreachable.

Code Block
bgColor#ccccff

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

Noncompliant Code Example (System.runFinalizersOnExit())

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.unmigrated-wiki-markup

According to the Java API \[ [API 2006|AA. Bibliography#API 06]\] class {{System}}, {{runFinalizersOnExit()}} method documentation2014] 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 prevents it from being garbage-collected but also prevents it from using calling its finalizer to close new resources that may have been allocated by the called method. As detailed in rule MET04 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 result in the observation of an 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; // mutableMutable instance field

  protected SubClass() {
    d = new Date();
  }

  protected void finalize() throws Throwable {
    System.out.println("Subclass finalize!");
    try {
      //  cleanupCleanup resources 
      d = null;				
    } finally {
      super.finalize();  // Call BaseClass's finalizer
    }
  }
	
  public void doLogic() throws Throwable {
    // anyAny resource allocations made here will persist 

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

Compliant Solution

...

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|the "initialized flag"–compliant solution discussed in OBJ11-J. Prevent access to partially initialized objects#OBJ04-EX1] discussed in rule [OBJ11-J. Prevent access to partially initialized objects]. As always, a good place to call the termination logic is in the {{finally}} . Be wary of letting constructors throw exceptions. As always, a good place to call the termination logic is in the finally block.

Exceptions

MET18MET12-J-EX0: Finalizers may be used when working with native code because the garbage collector cannot reclaim memory used by code written in another language and because the lifetime of the object is often unknown. Again, the native process must not perform any critical jobs that require immediate resource deallocation.

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.it is as follows:

Code Block
bgColor#ccccff

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

Wiki MarkupAlternatively, 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]\] 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 nonfinal classes. "The finalizer guardian forces super.finalize to be called if a subclass overrides finalize() and does not explicitly call super.finalize" [JLS 2015].

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

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

Risk Assessment

MET12-J-EX1: A class may use an empty final finalizer to prevent a finalizer attack, as specified in OBJ11-J. Be wary of letting constructors throw exceptions.

Risk Assessment

Improper use 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

MET18

MET12-J

medium

Medium

probable

Probable

medium

Medium

P8

L2

Related Vulnerabilities

AXIS2-4163

Related Guidelines

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="1fb87357-8a45-480c-8d2c-6c028aec7ead"><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()", [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()"

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="9d384b84-95e4-4db5-9972-857cca3462c8"><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="18394313-cc6a-4c3f-b8ad-e0d3775acf11"><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="3d136b85-ea1d-4cf9-9031-e9ff5c3ae309"><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="bcdd2adf-a8f2-43cd-8a3e-febab4311ad4"><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="1cdc0122-7315-467a-a701-47b7978db20b"><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="458aee5f-6613-4e36-9896-cefc2d407b08"><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="01660da7-d659-41ba-9e39-5e9f424cf956"><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>

Automated Detection

Tool
Version
Checker
Description
CodeSonar4.2FB.BAD_PRACTICE.FI_EMPTY
FB.BAD_PRACTICE.FI_EXPLICIT_INVOCATION
FB.BAD_PRACTICE.FI_FINALIZER_NULLS_FIELDS

FB.BAD_PRACTICE.FI_FINALIZER_ONLY_NULLS_FIELDS
FB.BAD_PRACTICE.FI_MISSING_SUPER_CALL
FB.BAD_PRACTICE.FI_NULLIFY_SUPER
FB.MALICIOUS_CODE.FI_PUBLIC_SHOULD_BE_PROTECTED
FB.BAD_PRACTICE.FI_USELESS

Empty finalizer should be deleted
Explicit invocation of finalizer
Finalizer nulls fields
Finalizer nulls fields
Finalizer does not call superclass finalizer
Finalizer nullifies superclass finalizer
Finalizer should be protected, not public
Finalizer does nothing but call superclass finalizer

Coverity7.5

CALL_SUPER
DC.THREADING
FB.FI_EMPTY
FB.FI_EXPLICIT_INVOCATION
FB.FI_FINALIZER_NULLS_FIELDS
FB.FI_FINALIZER_ONLY_NULLS_FIELDS
FB.FI_MISSING_SUPER_CALL
FB.FI_NULLIFY_SUPER
FB.FI_USELESS
FB.FI_PUBLIC_SHOULD_BE_ PROTECTED

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V

CERT.MET12.MNDF
CERT.MET12.FCF
CERT.MET12.FM
CERT.MET12.IFF
CERT.MET12.NCF
CERT.MET12.OF
CERT.MET12.EF
CERT.MET12.FCSF
CERT.MET12.MFP

Do not define 'finalize()' method in bean classes
Call 'super.finalize()' from 'finalize()'
Do not use 'finalize()' methods to unregister listeners
Call 'super.finalize()' in the "finally" block of 'finalize()' methods
Do not call 'finalize()' explicitly
Do not overload the 'finalize()' method
Avoid empty 'finalize()' methods
Avoid redundant 'finalize()' methods which only call the superclass' 'finalize()' method
Give "finalize()" methods "protected" access
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1113
S1111
S1174
S2151
S1114
The Object.finalize() method should not be overriden
The Object.finalize() method should not be called
"Object.finalize()" should remain protected (versus public) when overriding
"runFinalizersOnExit" should not be called
"super.finalize()" should be called at the end of "Object.finalize()" implementations

Related Vulnerabilities

AXIS2-4163 describes a vulnerability in the finalize() method in the Axis web services framework. The finalizer incorrectly calls super.finalize() before doing its own cleanup, leading to errors in GlassFish when the garbage collector runs.

Related Guidelines

MITRE CWE

CWE-586, Explicit call to Finalize()

CWE-583, finalize() Method Declared Public

CWE-568, finalize() Method without super.finalize()

Bibliography

[API 2014]

Class System
finalize()

[Bloch 2008]

Item 7, "Avoid Finalizers"

[Boehm 2005]


[Coomes 2007]

"'Sneaky' Memory Retention"

[Darwin 2004]

Section 9.5, "The Finalize Method"

[Flanagan 2005]

Section 3.3, "Destroying and Finalizing Objects"

[JLS 2015]

§12.6, "Finalization of Class Instances"


...

Image Added Image Added Image AddedMET17-J. Do not increase the accessibility of overridden or hidden methods      05. Methods (MET)      MET19-J. Ensure that keys used in comparison operations are immutable