...
- 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 lacks any guarantee that finalizers will execute on process termination. Methods such as
System.gc()
,System.runFinalization()
,System.runFinalizersOnExit()
, andRuntime.runFinalizersOnExit()
either lack such guarantees or have been deprecated because of lack of safety and potential for deadlock.
According to the _Java Language Specification_, [§12, §12.6.2, "Finalizer Invocations are Not Ordered"|http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.6.2] \[[JLS 2005|AA. References#JLS 05]\]:Wiki Markup
One consequence is that slow-running finalizers can delay execution of other finalizers in the queue. Further, the [JLS 2005]: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.
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.
...
- 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 must be protected from concurrent access. See the JavaOne presentation by Hans J. Boehm \ [[Boehm 2005|AA. References#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 neither the invocation order nor the specific executing thread or threads for finalizers can be guaranteed or controlled.
...
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.
According to the Java API \ [[API 2006|AA. References#API 06]\] class {{ Wiki Markup 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.
...
Code Block |
---|
Subclass finalize! Superclass finalize! This is sub-class! The date object is: null |
Compliant Solution
...
Joshua Bloch \ [[Bloch 2008|AA. 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 the "initialized flag" -- – compliant solution discussed in rule [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-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.
...
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 object forces {{super.finalize
}} to be called if a subclass overrides {{finalize()
}} and does not explicitly call {{supersuper.finalize
}}" \ [[JLS 2005|AA. 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 } }; //... } |
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET12-J | medium | probable | medium | P8 | L2 |
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. This leads to errors in GlassFish
when the garbage collector runs.
...
CWE-586. Explicit call to | |
| CWE-583. |
| CWE-568. |
Bibliography
[API 2006] | |||||
Item 7. Avoid finalizers | |||||
| |||||
"Sneaky" Memory Retention | |||||
Section 9.5, The Finalize Method | |||||
Section 3.3, Destroying and Finalizing Objects | |||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5dbc55d2-e529-4a33-8304-79820d067d23"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. References#API 06]] | [ | 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="1f136508-2b90-4277-ad3c-6be4503ef8a8"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. References#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="b65e6c73-4988-424f-a2d0-7850729fda8a"><ac:plain-text-body><![CDATA[ | [[Boehm 2005 | AA. References#Boehm 05]] |
| ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="d6664a8f-ad69-42c6-84d0-a62176e1e579"><ac:plain-text-body><![CDATA[ | [[Coomes 2007 | AA. References#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="ad225318-682e-4606-9629-83f52524cfce"><ac:plain-text-body><![CDATA[ | [[Darwin 2004 | AA. References#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="2bee9caf-4035-48af-aa74-94cb751fd7b2"><ac:plain-text-body><![CDATA[ | [[Flanagan 2005 | AA. References#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="d2bbc206-e21d-4eac-92e0-57233c008fe8"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. References#JLS 05]] | §12.6, Finalization of Class Instances ]]></ac:plain-text-body></ac:structured-macro> |
...