Before the The garbage collector acts on an object to reclaim it, invokes object finalizer methods after it determines that the object is unreachable but before it reclaims the object's finalizer is executed. This is required to ensure that storage. Execution of the finalizer provides an opportunity to release resources such as open streams, files, and network connections get freed since resource management does not happen automatically while reclaiming memory. In Java, the finalize
method of java.lang.Object
is used to perform this activity.that might not otherwise be released automatically through the normal action of the garbage collector.
A sufficient number of problems are associated with finalizers to restrict their use to exceptional conditionsThe caveats associated with the use of finalizers are discussed here:
- There is no fixed time for finalizers to get executed, which again 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.at which finalizers must be executed 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 an object'sfinalize()
method is problematic.
- The JVM may 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 some or all unreachable object. Finalization on process exit is also not guaranteedobjects. Consequently, attempts to update critical persistent state from finalizer methods can fail without warning. Similarly, Java lacks any guarantee that finalizers will execute on process termination. Methods such as
System.gc()
,System.runFinalization()
,System.runFinalizersOnExit()
, andRuntime.runFinalizersOnExit
are either just marginally better()
either lack such guarantees or have been deprecated due to because of lack of safety and potential for deadlock causing effects.
Wiki Markup According to the Java Language Specification: \[[JLS 05|AA. Java References#JLS 05]\] Section 12.6.2:
This can be a problem as slow running finalizers tend to block others in the queue.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.
- 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.
- According to The Java Language Specification (JLS), §12.6, "Finalization of Class Instances" [JLS 2015]:
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.The Java programming language imposes no ordering on
finalize()
method calls. Finalizers [of different objects] may be called in any order, or even concurrently.
- Uncaught exceptions thrown during finalization are ignored. When an exception 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 can cause objects to incorrectly remain reachable; consequently, their finalizers are never invoked.
- A programmer can unintentionally resurrect an object's reference in the
finalize()
method. When this occurs, A possibility exists such that the programmer unintentionally resurrects the references in thefinalize
method. While the garbage collector must determine yet again whether the object is free to be deallocated. Further, because thefinalize
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 below allocates a 16 MB buffer for backing a Swing
Jframe
. None of theJFrame
APIs have afinalize
method, however,JFrame
extendsAWT Frame
which has afinalize
method. The byte buffer continues to persist until thefinalize
method gets called and lasts for at least two garbage collection cycles.
Code Block |
---|
Class MyFrame extends Jframe {
private byte[] buffer = new byte[16 * 1024 * 1024]; // persists for at least two GC cycles
}
|
- It is also imprudent to use finalizers for reclaiming scarce resources by inviting garbage collection. Garbage collection usually depends on memory related traits and not on the scarcity of a particular resource. Thus, if memory is available aplenty, there is no reason for the scarce resource to not get exhausted despite the use of a finalizer. See FIO34-J. Ensure all resources are properly closed when they are no longer needed and CON02-J. Facilitate thread reuse by using Thread Pools for more on handling resources correctly.
- 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.
Wiki Markup 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 a finalizer is inevitable, the cleanup data structure should be protected from concurrent access (See \[[Boehm 05|AA. Java References#Boehm 05]\]).
Noncompliant Code Example
The System.runFinalizersOnExit()
method has been used in this noncompliant example to simulate a garbage collection run (note that this method is deprecated due to thread-safety issues).
Wiki Markup |
---|
According to \[[API 06|AA. Java References#API 06]\] class {{System}}, {{runFinalizersOnExit()}} 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 SubClass
overrides the protected finalize
method and performs cleanup. 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 use its finalizer anymore in order 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 and in the worst case result in the infamous NullPointerException
.
()
method has executed once, the garbage collector cannot invoke it a second time.
- Garbage collection usually depends on memory availability and usage rather than on the scarcity of some other particular resource. Consequently, when memory is readily available, a scarce resource may be exhausted in spite of the presence of a finalizer that could release the scarce resource if it were executed. See FIO04-J. Release resources when they are no longer needed and TPS00-J. Use thread pools to enable graceful degradation of service during traffic bursts for more details on handling scarce resources correctly.
- 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.
- 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 themain()
thread, although this property is not guaranteed. When a finalizer is necessary, any required cleanup data structures must be protected from concurrent access. See the JavaOne presentation by Hans J. Boehm [Boehm 2005] for additional information.
- Use of locks or other synchronization-based mechanisms within a finalizer can cause deadlock or starvation. This possibility arises because neither the invocation order nor the specific executing thread or threads for finalizers 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 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
object. Although the JFrame
APIs lack finalize()
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 | ||
---|---|---|
| ||
class MyFrame extends JFrame {
private byte[] buffer = new byte[16 * 1024 * 1024];
// Persists 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 | ||
---|---|---|
| ||
class MyFrame {
private JFrame frame;
private byte[] buffer = new byte[16 * 1024 * 1024]; // Now 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.
According to the Java API [API 2014] 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
that not only prevents it from being garbage-collected but also prevents it from calling its finalizer to close new resources that may have been allocated by the called method. As detailed in 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 result in the observation of an object in an inconsistent state. In some cases, this can result in NullPointerException
.
Code Block | ||
---|---|---|
| ||
class BaseClass {
| ||
Code Block | ||
| ||
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("SubclassSuperclass finalize!"); try {doLogic(); } public void //doLogic() throws cleanupThrowable resources { System.out.println("This d = null; is super-class!"); } finally} } class SubClass extends BaseClass { private Date d; // Mutable instance field protected super.finalizeSubClass(); { // call BaseClass' finalizer d = }new Date(); } publicprotected void doLogicfinalize() throws Throwable { /* any resource allocations made here will persist */ System.out.println("Subclass finalize!"); try { // inconsistent objectCleanup stateresources System.out.println("This is sub-class! The date object is: " + dd = null; } finally { super.finalize(); // Call BaseClass'd's isfinalizer already null } } public class BadUse { public static void maindoLogic(String[] args) { throws Throwable try { // Any resource BaseClassallocations bcmade =here new SubClass();will persist System.runFinalizersOnExit(true); // artificiallyInconsistent simulateobject finalizationstate (do not do this) System.out.println( } catch (Throwable t) { /* handle error */ } "This is sub-class! The date object is: " + d); // 'd' is already null } } |
A expected, this code outputs:
Code Block |
---|
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.
Code Block | ||
---|---|---|
| ||
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 from code written in another language. Also, the lifetime of the objects 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 next.
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. |
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] 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 "initialized flag"–compliant solution discussed in OBJ11-J. Be wary of letting constructors throw exceptions. As always, a good place to call the termination logic is in the finally
block.
Exceptions
MET12-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 it is as follows:
Code Block | ||
---|---|---|
| ||
protected void finalize() throws Throwable {
try {
//...
} finally {
super.finalize();
}
}
|
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 | ||
---|---|---|
| ||
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 while dealing with native code. For example, if object A
references object B
(either directly or reflexively) 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 done 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 will ensure 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
Finalizers can have unexpected behavior.
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
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] Section 12.6, Finalization of Class Instances
\[[API 06|AA. Java References#API 06]\] [finalize()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize()]
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 7, Avoid finalizers
\[[Darwin 04|AA. Java References#Darwin 04]\] Section 9.5, The Finalize Method
\[[Flanagan 05|AA. Java References#Flanagan 05]\] Section 3.3, Destroying and Finalizing Objects
\[[Coomes 07|AA. Java References#Coomes 07]\] "Sneaky" Memory Retention
\[[Boehm 05|AA. Java References#Boehm 05]\]
\[[MITRE 09|AA. Java References#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", [CWE ID 568|http://cwe.mitre.org/data/definitions/568.html] "finalize() Method Without super.finalize()" |
//...
}
|
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.
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 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 |
---|---|---|---|---|---|
MET12-J | Medium | Probable | Medium | P8 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar | 4.2 | FB.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 | ||||||
Coverity | 7.5 | CALL_SUPER | Implemented | ||||||
Parasoft Jtest |
| CERT.MET12.MNDF | 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 |
| 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
CWE-586, Explicit call to CWE-583, CWE-568, |
Bibliography
[API 2014] | |
Item 7, "Avoid Finalizers" | |
"'Sneaky' Memory Retention" | |
Section 9.5, "The Finalize Method" | |
Section 3.3, "Destroying and Finalizing Objects" | |
[JLS 2015] |
...
OBJ01-J. Understand how a superclass can affect a subclass 06. Object Orientation (OBJ) OBJ03-J. Be careful about final reference