Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Setting local reference variables to null to "help the garbage collector"€ is unnecessary. It adds clutter to the code and can make maintenance difficult. Java just-in-time compilers (JITs) can perform an equivalent liveness analysis; in fact, and most implementations do so.

A related bad practice is use of a finalizer to null out references. See MET12-J. Do not use finalizers for additional details.

This guideline applies specifically to local variables. For a case where explicitly erasing objects is useful, see OBJ55-JG49. Remove short-lived objects from long-lived container objects.

Noncompliant Code Example

...

This compliant solution uses a lexical block to control the scope, and consequently the lifetime , of the buffer object:

Code Block
bgColor#ccccff
{ // Limit the scope of buffer
  int[] buffer = new int[100];
  doSomething(buffer);
}

...