Re: Nulling an object
Frank Cisco wrote:
If you null and object ie. obj = null, when is it cleared from memory?
Immediately or at the next garbage collection?
Arne Vajh?j wrote:
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.
To amplify on what Arne said, you don't "null an object". That doesn't exist.
After all references ("refs") to an object disappear, the object might be
reclaimed by garbage collection (GC). Or it might not. Ever.
Note that there is very rarely any use for explicit nulling
in Java. Having the ref not being ref'ed any more is sufficient.
There are occasional exceptions, as explained by Josh Bloch in /Effective
Java/, Item 6 - essentially when you have logic that manages memory in a way
additional to mere allocation, you have to dereference such extra management.
Put more clearly, when you have hidden references to an object, such as in a
collection like a Stack, those references keep an object alive even after the
program is through with it. That's called "unintentional object retention",
or "packratting". You might have to null out those hidden references, but
other than in that specific situation you don't have to and shouldn't.
--
Lew