I've tried to figure out how many objects are eligible for GC.
Below, please find the code which I've modified a bit in order to see WHICH objects are eligible:
The correct answer is 2 - and indeed, running the code above, I get object 3 and 4 beeing eligible for GC.
Nevertheless, I've tried in vain to figure out why.
To resolve this, I've painted the following diagram:
In my opinion, object 3 and 4 would be isolated (and thus eligible for GC) only if line 6 (coming from object 4 back to object 1) didn't exist.
But maybe, I've misunderstood a detail?
Is something wrong with my diagram? Or did I oversee something?
I think (and I'm not an expert because I'm figuring this out too), it's because there is no reference from the stack. Since the s1 reference only reaches out to A2, A3 and A4 cannot be reached. Therefore they are eligible for gc.
why are the last two objects eligible for GC, if there's still a connectionn (line 6) from A(4) to A(1)?
As Maren said, the connection 6 doesn't let you access the last two objects from your code. The last two objects are inaccessible now, thus they are eligible for GC...
Joined: Apr 15, 2010
Thank you, Ankit, Mohitkumar and Maren!
Now I think I'm able to locate the main issue: line 6 goes back from A(4) to A(1) (arrow pointing to the left), but it deals only with a "passive" connection.
It seems that with object references, it behaves according to the famous Hollywood principle: "don't call us, we call you".
Consequently, the JVM doesn't care about line 6 - if line 6 pointed into the opposite direction, instead, A(4) would not be eligible for GC.
Hope I'm right ... when this thread is closed, I'll remove my painting above, trying to exhibit it in the Museum of Modern Art ;-))