I just read this article: The Truth About Garbage Collection
Section "A.3.3 Invisible" explains how and when an object goes into invisible state.
In the code below, the object assigned to the variable foo will become invisible after exiting the try/catch and will remain on a strong link until the run method exits (which will never happen, since the while loop runs forever).
public void run() { try { Object foo = new Object(); foo.doSomething(); } catch (Exception e) { // whatever } while (true) { // do stuff } // loop forever }
This article says:
However, an effective JVM implementation is hardly a null reference when it goes beyond the scope.
Why is this not effective?
My attempt at explanation is as follows:
Say that the stack for this method contains four elements, and now an invisible object is at the bottom.
If you want to instantly assemble an object, you will need to place and save three elements, pop and drop the fourth element, and then return the three still valid elements back to the stack.
If you collect an invisible object after the control flow leaves the run method, the virtual machine could just put all four elements and discard them.
source share