A question about GC
This is a quesiton taken from a java exam,
How many objects are eligible for ga开发者_开发知识库bage collection at #1 ?
public class Main {
Integer x = 32768;
public static void main(String[] args)
{
Main m = new Main();
m = null;
// #1
}
}
I thought it just collect Integer x, does GC even collect the Main object m?
Yes, it does collect Main object. Since integer is neither a separate object by itself (it's a member of Main) not a pointer it won't be collected separately but only as a part of Main.
Two objects may be deleted by the garbage collector.
The object assigned to m is not reachable any more, nor is the Integer inside Main.
Edit: You can ask yourself: "Is it possible that I access the object in some way at this point?" If the answere is "No", the garbage collector may delete it.
One bit of confusion you may be having is that the main method can be called without there even being a main object in existence. That is because it is a static method. Similarly, the "Integer x" only exists as a field in a main object. So when you create a new Main object m you also create the integer m.x as part of m. Then when you set m to null the object that was previously referred to by m is garbage and can be collected.
Now, when will it be collected is a totally different question. There are really are no guarantees; however, since its use was so localized it will almost certainly be taken care of at the next minor collection/scavenge/pick-your-favorite'-terminology.
It could. There is no reference to it anymore, so it is eligible for garbage collection.
The instance of Main
is eligible for garbage collection and normally the Integer will also be eligible. But the Integer instance can also be cached by the Integer
class if configured to do so (see this answer).
Normally only integers between -128 and 127 are cached when using Integer#valueOf(int) (used for autoboxing) but the upper limit can be increased by setting the system property java.lang.Integer.IntegerCache.high
My observations using a recent OpenJDK have shown that only once a method exits do any references it orphaned actually get collected. I did not expect this at all, but it's what happened. Extracting those lines of code into another method, which would then return back to main(), did allow the instance to be collected.
I think this is a dumb question. (EDIT: I mean the exam question! Not insulting the submitter!) It's all in how you define "eligible". In my case, I'd say once there were no references left, the instance was eligible to be collected, it's just that it never would actually be collected until sometime after the method returns.
精彩评论