- Objects created near the head of the call stack (say, main) that
remain in scope for a very long time, even though they are no longer
needed. I suspect that there are ways of organizing the code so as to
eliminate that behavior, but perhaps just setting the reference to
null when finished with it is the simplest thing.
I have a vague recollection of this question coming up previously, but
don't remember exactly what the conclusion was.
For context: I assume the above statement is referring to a situation like
this:
void method()
{
object ref = ...;
sub_methodA(ref);
sub_methodB();
sub_methodC();
}
With the proposal that one assign "null" to the variable "ref" immediately
after the call to sub_methodA().
The thing I can't remember is whether Java's JITter and GC deal with this
automatically. In .NET (which I'm somewhat more familiar with), they do.
That is, the JIT compiler can tell the variable isn't used past a certain
point, and the GC treats the reference as unreachable past that point. In
fact, assigning "null" to the variable can actually delay collection,
because it causes the variable to be used at a later point in the code
than without such an assignment.
I actually didn't think this through completely. "ref" in the example above
is unused after method a, and GC should realize it. Depending on usage, the
certainly after.