K
Knute Johnson
John said:An object automatically becomes eligible for garbage collection when it
ceases to be reachable from any live thread via a chain of strong
(normal) references. That is the only criterion. Modern VMs typically
do not monitor assignment statements to make that determination; instead
they periodically trace reference chains to find which objects need to
be /kept/.
In the example you present, the Object created at the top of each loop
iteration becomes eligible for GC as soon as a new reference is assigned
to variable o, *provided that* the old Object's reference has not been
assigned to some object that persists across loop iterations. (For
example, if the loop added the object to a List then the Object would
not become eligible for GC before the List did.)
Local variables occupy space on the stack, but the number of local
variable slots in a stack frame is determined by the compiler. Almost
certainly, each iteration of the loop will use the same slot to
represent variable o. Even if different slots were used, the stack
frame size is fixed at compile time, so an infinite loop will quickly
have to start reusing variable slots, so you will not get a memory leak
from this direction.
When a thread returns from a method, its stack frame for that method
invocation is popped, freeing all the memory occupied by the local
variables of that method for that invocation. This isn't garbage
collection per se, but I think it addresses your concern even better.
Thanks John and everybody else that answered. I appreciate the time and
effort for my enlightenment.