2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-05-31 15:18:21 +02:00
Before it reclaims storage from an object that is no longer referenced, the garbage collector calls `finalize()` on the object.
2021-04-28 18:08:03 +02:00
2023-05-31 15:18:21 +02:00
But there is no guarantee that this method will be called as soon as the last references to the object are removed.
It can be few microseconds to few minutes later.
For this reason relying on overriding the `finalize()` method to release resources or to update the state of the program is highly discouraged.
=== What is the potential impact?
More unexpected issues can be caused by relying on the `finalize()` method to perform important operations on the application state:
2023-06-06 16:33:23 +02:00
* The JVM might terminate without ever calling this method on a particular object, leaving an unexpected or incomplete state of the program
* Uncaught exceptions will be ignored inside this method, making it harder to detect issues that could have been logged otherwise
* Finalizer methods can also be invoked concurrently, even on single-threaded applications, making it hard to maintain desired program invariants
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 18:08:03 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 18:08:03 +02:00
----
public class MyClass {
2023-06-06 16:33:23 +02:00
@Override
2024-02-26 17:10:45 +01:00
protected void finalize() { // Noncompliant
releaseSomeResources();
2021-04-28 18:08:03 +02:00
}
2023-06-06 16:33:23 +02:00
2021-04-28 18:08:03 +02:00
}
----
2024-02-26 17:10:45 +01:00
=== Exceptions
It is allowed to override the `finalize()` method as `final` method with an empty body, to prevent the _finalizer attack_ as described in _MET12-J-EX1_.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 18:08:03 +02:00
2023-05-31 15:18:21 +02:00
* https://docs.oracle.com/javase/specs/jls/se17/html/jls-12.html#jls-12.6[docs.oracle.com] - Finalization of Class Instances
2021-04-28 18:08:03 +02:00
* https://wiki.sei.cmu.edu/confluence/x/4jZGBQ[CERT, MET12-J.] - Do not use finalizers
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Do not override the "Object.finalize()" method
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== on 4 Jul 2013, 11:50:57 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-196
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]