Another confuddling question explanation by whizlabs here.
When the program reaches line 8, how many of the String objects created in line 5 are eligible for garbage collection? Assume that the System.out object is not keeping a reference.
A. - None B. - 1 C. - 10 D. - 11
My answer - D. Whizlabs answer - C.
C is correct. Answer A and B are wrong and C is correct because only the last String object of the 11 created still has a reference. Answer D is wrong because even though the mp variable is out of scope in line 8, the local variable still has a reference.
It was my understanding that no matter how many references an object has as long as they are unreachable (like the local String tmp in this case) the object is eligible for garbage collection. Am I wrong on this one?
Why is it still on the stack at that point? Is it not local to the block of the for loop and hence ceases to exist once you exit that block? If that is not the case then what is the exact rule on when it will get wiped and how come you can redeclare the variable on each successive iteration of the loop? If the tmp symbol is bound then you shouldn't be able redeclare, and if it's not bound then you should be able to garbage collect the string.
Joined: Apr 10, 2005
When tmp goes out of scope, the object it references is no longer accessible to any live thread, so the object becomes eligible for garbage collection right away when the loop ends. Therefore, I agree with Sergei that the correct answer is 11. The whizlabs explanation
Answer D is wrong because even though the tmp variable is out of scope in line 8, the local variable still has a reference
makes me ask, "What local variable? The tmp local variable that has gone out of scope and is unreachable by any live thread?" If that's the variable they mean, then this criteria for determining when an object becomes eligible for garbage collection runs counter to the explanation in K&B p. 432 which reads
we can now say with stunning clarity and resolve that, an object is eligible for garbage collection when no live thread can access it.
I've checked the K&B errata page and found no alterations made to their claim. As far as I know, when a variable goes out of scope, it is no longer reachable by a live thread, and is therefore immediately made eligible for garbage collection.