Before the The garbage collector acts on an object to reclaim it, invokes object finalizer methods after it has determined 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 are released as resource management does not happen automatically when memory is reclaimed, whose resources may not otherwise be released automatically through the normal action of the garbage collector. In Java, the finalize()
method of java.lang.Object
is used for this purpose.
There are a number of caveats associated with the use of finalizers:
- There is no fixed time for finalizers to get at which finalizers must be executed; this detail is JVM dependent: . The only thing that is guaranteed guarantee is that if 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 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 reclaims the associated object's storage (during the garbage collector's second cycle). Execution of an object's finalizer can be delayed for an arbitrarily long time . No after the object becomes unreachable. Consequently, avoid implementing time-critical functionality should be implemented in the in an object's
finalize()
method. For instance, closing file handles is not recommended.
- Do not depend on a finalizer for updating critical persistent state: It is possible for the JVM to The JVM can terminate without invoking the finalizer on an unreachable object. Finalization on process termination is also not guaranteed to work. Methods some or all unreachable objects. Consequently, attempts to update critical persistent state from finalizer methods can fail without warning. Similarly, Java provides no 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 because of lack of safety and potential for deadlock causing effects.
Wiki Markup According to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\] Section 12.6.2 "Finalizer Invocations are Not Ordered"
This can be a problem as slow running finalizers tend to block others 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.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 Effect of uncaught exceptions: An uncaught exception thrown during finalization is are ignored. The finalization process itself stops immediately so it , and consequently fails to accomplish its sole purpose.
- Coding errors that result in memory leaks can also cause finalizers to never execute to completionprevent execution of finalizers for objects that incorrectly remain reachable.
- A programmer may can unintentionally resurrect the object's reference in the
finalize()
method. While When this occurs, the garbage collector must determine yet again whether the object is free to be deallocated. Further, because thefinalize()
method is not invoked again.has executed once, the garbage collector cannot invoke it a second time.
- Superclasses Superclasses that use finalizers bring impose additional burden to constraints on their extending classes. Consider an example from JDK 1.5 and earlier. The code snippet below allocates a 16 MB buffer for backing used to back a Swing
Jframe
. None Although none of theJFrame
APIs have afinalize()
method, however,JFrame
extendsAWT Frame
which has does have afinalize()
method. The byte buffer continues to persist until its When aMyFrame
object becomes unreachable, the garbage collector cannot reclaim the storage for the byte buffer because code in the inheritedfinalize()
method gets called, and persists for at least two garbage collection cyclesmight 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 } |
- It is also imprudent to use finalizers for reclaiming scarce resources by enforcing Avoid using finalizers to reclaim scarce resources as a side-effect of garbage collection. Garbage collection usually depends on memory related traits and not availability and usage rather than on the scarcity of a some other particular resource. As a resultConsequently, if when memory is readily available, a scarce resource may get be exhausted even in spite of the presence of a finalizer that could reclaim 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 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 Finalizers interfere with the operation of modern generational garbage collectors . Another trap unfolds while trying to finalize reachable objects, an exercise that is always counterproductive.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
Wiki Markup It is not advisable to use any lock or sharing based mechanisms within a finalizer because of the inherent dangers of deadlock and starvation. On the other hand, it is 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 theThe {{finalize()}} methods are called from their own threads (notinvoked 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. IfWhen a finalizer is necessary, any therequired cleanup data structurestructures 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.
Noncompliant Code Example
This noncompliant code example uses the System.runFinalizersOnExit()
method to simulate a garbage collection run (note . Note that this method is deprecated because of thread-safety issues. (See ; see guideline MET15-J. Do not use deprecated or obsolete methods. )
Wiki Markup |
---|
According to the Java API \[[API 2006|AA. Bibliography#API 06]\] class {{System}}, {{runFinalizersOnExit()}} method documentation |
...
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
is reachable before A
's finalizer has concluded. This can be achieved 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 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
doesn't persist longer than expected 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 } |
...
Related Vulnerabilities
Bibliography
Wiki Markup |
---|
Wiki Markup |
\[[JLS 2005|AA. Bibliography#JLS 05]\] Section 12.6, Finalization of Class Instances \[[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]\] \[[BlochCoomes 20082007|AA. Bibliography#BlochBibliography#Coomes 0807]\] Item 7, Avoid finalizers "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 \[[CoomesJLS 20072005|AA. Bibliography#CoomesBibliography#JLS 0705]\] "Sneaky" Memory Retention \[[Boehm 2005|AA. Bibliography#Boehm 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()" |
...