Re: Nulling an object
Peter Duniho wrote:
In fact, even the example Lew gives of a Stack is in reality unlikely to
require specific handling. In particular, if you're actually _done_
Joshua Bloch and Brian Goetz and Sun generally disagree with you. If the
Stack lives a long time, items being popped from it might need to have the
popped element in the Stack nulled out, or else the stack itself keeps the
object reachable, depending on the implementation.
<http://www.ibm.com/developerworks/library/j-jtp01274.html>,
which references
<http://java.sun.com/developer/TechTips/1997/tt0903.html#tip2>
Item 6 of /Effective Java/ makes substantially the same point, with a more
thorough explanation.
<http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA24>
with the Stack, simply getting rid of the reference to the Stack itself
is sufficient for releasing all the objects that the Stack itself
references. Once the Stack becomes unreachable, so too do all the
objects the Stack references (assuming they aren't referenced elsewhere,
of course). It's only if you intend to retain the Stack, but no longer
want the objects to which it refers do you need to do any clearing of
references (and of course, the most direct way to do that is simply to
call the clear() method).
(Of course, in the real world a Stack is usually not discarded until
empty, at which point it doesn't have references to other objects
anyway, but that's not really germane to the point here :) ).
It is germane in the reverse, wherein the Stack is not yet discarded but you
wish references above the current top of stack to be.
The key is that constructs like Stack and Map take over part of the memory
management burden and hold on to references in ways that the programmer might
forget. This "packratting", long-lived structures holding on to
now-irrelevant references, is the source of so-called "memory leaks" in Java.
Goetz, in the above-referenced DeveloperWorks article, cautions against taking
this principle too far.
Another solution to packratting involves WeakReferences.
--
Lew