...
- A programmer can unintentionally resurrect an object's reference in the
finalize()
method. When this occurs, the garbage collector must determine yet again whether the object is free to be deallocated. Further, because thefinalize()
method has executed once, the garbage collector cannot invoke it a second time.
- Superclasses that use finalizers impose additional constraints on their extending classes. Consider an example from JDK 1.5 and earlier. The code snippet below allocates a 16 MB buffer used to back a Swing
Jframe
object. Although none of theJFrame
APIs have afinalize()
method,JFrame
extendsAWT.Frame
which does have afinalize()
method. When aMyFrame
object becomes unreachable, the garbage collector cannot reclaim the storage for the byte buffer because code in the inheritedfinalize()
method might refer to it. Consequently, the byte buffer must persist at least until the inheritedfinalize()
method for classMyFrame
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
}
|
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. In the MyFrame
example, the following code 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
}
|
- Avoid using finalizers to release scarce resources as a side-effect of garbage collection. 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 guidelines FIO06-J. Ensure all resources are properly closed 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 should be protected from concurrent access. See \[[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 the invocation order and the executing thread or threads for finalizers cannot be guaranteed or controlled.
...
- Do not use finalizers to release scarce resources as a side-effect of garbage collection. 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 guidelines FIO06-J. Ensure all resources are properly closed 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 should be protected from concurrent access. See \[[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 the invocation order and the executing thread or threads for finalizers cannot be guaranteed or controlled.
Because of these problems, finalizers must not be used in new classes.
Noncompliant Code Example (Superclass 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 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
}
|
Compliant Solution (Superclass 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; see guideline MET15-J. Do not use deprecated or obsolete classes or methods.
...
Code Block | ||
---|---|---|
| ||
class BaseClass { protected void finalize() throws Throwable { System.out.println("Superclass finalize!"); doLogic(); } { publicprotected void doLogicfinalize() throws Throwable { System.out.println("This is super-classSuperclass finalize!"); } } class SubClass extends BaseClass { private Date d; // mutable instance field protected SubClass() { d = new DatedoLogic(); } protectedpublic void finalizedoLogic() throws Throwable { System.out.println("Subclass finalizeThis is super-class!"); } } class SubClass tryextends BaseClass { private Date d; // mutable cleanupinstance resources d = null; field } finallyprotected SubClass() { d = new super.finalizeDate(); //} Call BaseClass's finalizer }protected void finalize() throws Throwable { } public void doLogic() throws ThrowableSystem.out.println("Subclass finalize!"); try { // any resourcecleanup allocationsresources made here will persist d // inconsistent object state= null; System.out.println("This is sub-class! The date object is: " + d} finally { super.finalize(); // Call BaseClass'd's isfinalizer already null } } public class BadUse { public static void maindoLogic(String[] args) { throws Throwable try { // any BaseClassresource bcallocations =made new SubClass(); here will persist // 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
This compliant 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().
}
...
}
|
...
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
}
}
}
|
This code outputs:
Code Block |
---|
Subclass finalize!
Superclass finalize!
This is sub-class! The date object is: null
|
Compliant Solution
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 first exception|OBJ05-J. Prevent access to partially initialized objects#OBJ04-EX1] discussed in guideline [OBJ05-J. Prevent access to partially initialized objects]. As always, a good place to call the termination logic is in the {{finally}} block. |
Exceptions
MET18-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.
...
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
Improper use of finalizers can result in resurrection of garbage-collection ready objects and result in denial of service vulnerabilities.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MET18-J | medium | probable | medium | P8 | L2 |
Related Vulnerabilities
Bibliography
Wiki Markup |
---|
\[[API 2006|AA. Bibliography#API 06]\] [finalize()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize()] \[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 7, Avoid finalizers \[[Boehm 2005|AA. Bibliography#Boehm 05]\] \[[Coomes 2007|AA. Bibliography#Coomes 07]\] "Sneaky" Memory Retention \[[Darwin 2004|AA. Bibliography#Darwin 04]\] Section 9.5, The Finalize Method \[[Flanagan 2005|AA. Bibliography#Flanagan 05]\] Section 3.3, Destroying and Finalizing Objects \[[JLS 2005|AA. Bibliography#JLS 05]\] Section 12.6, Finalization of Class Instances \[[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", [CWE ID 568|http://cwe.mitre.org/data/definitions/568.html] "finalize() Method Without super.finalize()" |
...