Re: how many objects r eligible for garbage Collection ?
Mark Thornton wrote:
Naveen Kumar wrote:
I am confused by someone over object creation in java.. Here is a
sample question..
class Card {
Short story=5;
Card go(Card c)
{
c=null;
return c;
}
public static void main(String[] args)
{
Card c1=new Card();
Card c2=new Card();
Card c3=c1.go(c2);
c1=null;
//do stuff;
}
when //do stuff is reached How many Objects are eligible for garbage
Collection ?
Unless c2 is used in 'do stuff' then all the objects are eligible for
collection. Merely having a local reference to an object is not
sufficient to keep the object. Local references are deemed not to exist
beyond their last point of use. This is not just theoretical either, the
current Java 6 from Sun does this.
....
More generally, I think this thread has failed to fully distinguish two
concepts:
1. Is an object unreachable, and therefore eligible for finalization?
The test here is whether the object can be accessed by any continuing
computation in any active thread. This is a property of the program and
the language specification, regardless of JVM implementation.
2. Will a particular JVM GC implementation, when dealing with a memory
shortage, notice that, and collect it. This is subject to change as JVMs
become more sophisticated.
Unreachability is not, in general, computable. The JVM has to
approximate it. Given the disastrous consequences of collecting a
reachable object, it has to err in the direction of not collecting some
unreachable objects. There will never be a perfect garbage collector
that collects every unreachable object and no others.
Patricia