rspec/rules/S2165/java/rule.adoc

74 lines
2.3 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This rule raises an issue when a finalizer assign `null` to fields of the instance it is called on.
== Why is this an issue?
In the Java object lifecycle, the `finalize` method for an instance is called
after the garbage collector has determined that the instance can be removed from the object heap.
Therefore, it is unnecessary to implement a finalizer to set instance fields explicitly to `null`
to tell the garbage collector that the instance no longer needs them.
In the worst case, implementing `finalize` is even counterproductive because it might accidentally create new references
from other (living) objects on the heap to the collectible instance, thus, reviving it.
**Important note about finalizers:**
There are no guarantees when the Java Runtime will call the `finalize` method or whether it will be called at all.
Using finalizers is, therefore, a bad practice. They should never be used to free resources,
such as closing streams, freeing locks, or freeing native system resources.
Consider other freeing mechanisms instead, such as an explicit `close`, `unlock`, or `free` method in your class.
== How to fix it
Remove assignments from your finalizer that assign `null` to fields of the instance the finalizer is called on.
When this leaves you with an empty finalizer body, remove the finalizer.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public class Foo {
private String name;
@Override
void finalize() {
name = null; // Noncompliant, instance will be removed anyway
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public class Foo { // Compliant
private String name;
}
----
== Resources
=== Documentation
* https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#finalize--[Java SE 8 API Specification - Object.finalize]
=== Articles & blog posts
* https://howtodoinjava.com/java/basics/why-not-to-use-finalize-method-in-java[Java finalize() Why We Should Not Use It? - Lokesh Gupta]
* https://www.baeldung.com/java-finalize[A Guide to the finalize Method in Java - Baeldung]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this nullification of "xxx".
endif::env-github,rspecator-view[]