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 because this depends on the 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()
, 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 \[[JLS 2005|AA. Bibliography#JLS 05]\], §12 , [§12.6.2, "Finalizer Invocations are Not Ordered ,"|"[JLS 2005]:Wiki Markup
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.unmigratedunmigrated-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.
- 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 Java Language Specification 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.
...
- 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 See rules FIO04-J. Close 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.
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 shouldmust be protected from concurrent access. See \[[Boehm 2005|AA. Bibliography#Boehm 05]\] for additional information.
...
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 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 | ||
---|---|---|
| ||
class MyFrame extends JFrame {
private byte[] buffer = new byte[16 * 1024 * 1024];
// persists for at least two GC cycles
}
|
...
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.
...
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 prevented 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 rule 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 object in an inconsistent state. In some cases, this can result in the infamous NullPointerException
.
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("Subclass finalize!"); try { // cleanup resources d = null; } finally { super.finalize(); // Call 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(); // Artificially simulate finalization (do not do this) System.runFinalizersOnExit(true); } catch (Throwable t) { // Handle error } } } |
...
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 the [the first exception"Initialized Flag" - compliant solution|OBJ11-J. Be wary of letting constructors throw exceptions#OBJ04-EX1] discussed in rule [OBJ11-J. Prevent access to partially initialized objects|OBJ11-J. Be wary of letting constructors throw exceptions]. As always, a good place to call the termination logic is in the {{finally}} block. |
...
Code Block | ||
---|---|---|
| ||
protected void finalize() throws Throwable { try { //... } finally { super.finalize(); } } |
Wiki Markup |
---|
Alternatively, aA 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-finalnonfinal 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]\]. |
...
Improper use of finalizers can result in resurrection of garbage-collection-ready objects and result in denial-of-service vulnerabilities.
...
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.
Related Guidelines
CWE-586, ". Explicit Call call to | |
| CWE-583, ". |
| CWE-568, ". |
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="02bd7df00f9f78e0-514d9d11-424841d1-8a2f88ba-f049da95bbe37e95e79deaa6"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#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="d0a07098cc4dfd39-5a70aa55-44e54376-b964b5cf-101ac2f065c7538cf486a96a"><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="a4e07c452aee27df-08d0b5dc-46584d28-a363b848-8ea228aa2bc88b1f01f00b84"><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="088a9d459b8f57d6-98a7ad87-473b41fb-8c36bfa3-d75c103ffbc9062c2a827793"><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="326ed1c32dc73846-e8a17ea3-459c4e5e-a6139515-75b41a8c9b95e5b1abd5fe2a"><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="f1b297b84b0b238b-5126111c-413f466a-928caa39-9122560de578d83735d76724"><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="30d806cd3936aa3b-abe11456-45b4421e-ab2594cc-f95219664273b8d02fce6dfa"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | §12.6, Finalization of Class Instances | ]]></ac:plain-text-body></ac:structured-macro> |
...