Setting local reference variables to null
to "help the garbage collector" is unnecessary. It adds clutter to the code and can introduce subtle bugsmake maintenance difficult. Java just-in-time compilers (JITs) can perform an equivalent liveness analysis; in fact, and most implementations do thisso.
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-J. Remove short-lived objects from long-lived container objects.
Noncompliant Code Example
In this noncompliant code example, buffer
is a local variable that holds a reference to a temporary array. The programmer attempts to help the garbage collector by assigning null
to the buffer
array when it is no longer needed.
Code Block | ||
---|---|---|
| ||
{ // localLocal scope ... int[] buffer = new int[100]; doSomething(buffer); buffer = null // No need to explicitly assign null ...; } |
Compliant Solution
Program logic occasionally requires tight control over the lifetime of an object referenced from a local variable. In the unusual cases where such control is necessary, use a lexical block to limit the scope of the variable because the garbage collector can collect the object immediately when it goes out of scope [Bloch 2008].
This compliant solution uses a lexical block to control the scope, and consequently the lifetime , of the buffer
object.:
Code Block | ||
---|---|---|
| ||
{ // limitLimit the scope of buffer int[] buffer = new int[100]; doSomething(buffer); } |
Applicability
It is unnecessary to set local reference variables to null
when they are no longer needed in a mistaken attempt to help the garbage collector recover their spacereclaim the associated memory.
Bibliography
Item 6: , "Eliminate obsolete object referencesObsolete Object References" |
...