Versions Compared

Key

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

...

Reference nulling to "help the garbage collector" is not necessary at all. In fact, it just adds clutter to the code and may lead to bugs. Assigning null to local variables is also not very useful as JIT can equivalently do a liveness analysis. Perhaps the worst one can do is to use a finalizer to null out references, thereby befriending a huge performance hit.

Code Block
bgColor#FFCCCC
int[] buffer = new int[100];
doSomething(buffer);
buffer = null  // no need for explicitly assigning null

Wiki Markup
The code snippet shown below improves on the discouraged practice by narrowing down the scope of the variable {{buffer}} so that the garbage collector collects the object as soon as it goes out of scope. \[[Bloch 08|AA. Java References#Bloch 08]\]

Code Block
bgColor#ccccff

{ // limit the scope of buffer 
  int[] buffer = new int[100];
  doSomething(buffer);
}

Array based data structures such as ArrayLists are an exception since the programmer has to explicitly set only a few of the array elements to null to indicate their demise.

...

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class {{System}}
\[[Commes 07|AA. Java References#Commes 07]\] Garbage Collection Concepts and Programming Tips
\[[Goetz 04|AA. Java References#Goetz 04]\] 
\[[Lo 05|AA. Java References#Lo 05]\] 
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 6: "Eliminate obsolete object references"
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 405|http://cwe.mitre.org/data/definitions/405.html] "Asymmetric Resource Consumption (Amplification)" 

...