rspec/rules/S2165/java/rule.adoc

74 lines
2.3 KiB
Plaintext
Raw Normal View History

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.
2021-04-28 16:49:39 +02:00
== 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.
2021-04-28 16:49:39 +02:00
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
public class Foo {
private String name;
@Override
void finalize() {
name = null; // Noncompliant, instance will be removed anyway
2021-04-28 16:49:39 +02:00
}
}
----
==== 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[]