== Why is this an issue?

Before it reclaims storage from an object that is no longer referenced, the garbage collector calls `finalize()` on the object.

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:

* 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

=== Noncompliant code example

[source,java]
----
public class MyClass {

  @Override
  protected void finalize() { // Noncompliant
    releaseSomeResources();
  }

}
----

=== 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_.

== Resources

* https://docs.oracle.com/javase/specs/jls/se17/html/jls-12.html#jls-12.6[docs.oracle.com] - Finalization of Class Instances
* https://wiki.sei.cmu.edu/confluence/x/4jZGBQ[CERT, MET12-J.] - Do not use finalizers


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Do not override the "Object.finalize()" method


'''
== Comments And Links
(visible only on this page)

=== on 4 Jul 2013, 11:50:57 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-196

endif::env-github,rspecator-view[]
