On Sun, 17 May 2009, Arne Vajh?j wrote:
Frank Cisco wrote:
If you null and object ie. obj = null, when is it cleared from
memory? Immediately or at the next garbage collection?
You null a ref to an object. The object that the ref previously
pointed to will be GC'ed after that assuming that there are no other
refs to it.
Note that there is very rarely any use for explicit nulling in Java.
Having the ref not being ref'ed any more is sufficient.
The only time it's important is where you have a reference from a
long-lived structure to a large structure that you no longer need. The
long-lived structure can be an object or a stack frame. If you're
writing a class where the lifetime is unknown (a library class, say),
and the size of the referent is large or unknown, i think it's prudent
to null out the variable when you can. ArrayList nulls out slots in its
array when elements are removed, for example; ISTR that an early version
didn't, and that this led to hard-to-debug memory leaks.
An example of the stack frame case was a program i worked on a little
while ago which looked like:
public void main(String[] args) {
BigXMLDocument conf = loadConfigFile();
Problem prob = initialiseProblem(conf);
prob.solve();
printResult(prob);
}
The XML tree for the config file wasn't needed after the creation of the
problem object, but because the reference to it was still live, it
couldn't be collected, and so sat around wasting memory while the
long-running solve method ran. Explicitly setting the variable to null
before going into solve would have avoided this.
This is much better than explicit nulling.