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

public class Foo {
  private String name;

  @Override
  void finalize() {
    name = null;  // Noncompliant, instance will be removed anyway
  }
}

Compliant solution

public class Foo { // Compliant
  private String name;
}

Resources

Documentation

Articles & blog posts