Does the object which is the entry point of a Java program get garbage collected?

丶灬走出姿态 提交于 2020-01-06 04:10:06

问题


If I have a class Sample and I have an instance method, instanceMethod in it. The class has a main method where I create an object of Sample itself and call it's instanceMethod without using a reference variable.

like this:

new Sample().instanceMethod();

inside the main.

Since this object has NO reference, will the garbage collector collect it ?


回答1:


In Java1, I don't believe the object can be collected while instanceMethod() is being executed. In the main method's stack frame there is a reference to the object, at least logically (the JIT compiler may elide it). The fact that you're not assigning it to a variable doesn't affect the bytecode very much.

Of course when instanceMethod() completes, the object may be eligible for garbage collection - but it may not. For example, instanceMethod() may store a reference to this in a static variable.

Basically it's not worth getting hung up over intricate corner cases - just rely on the GC collecting objects which can't be reached any more in any way, but not collecting objects which may still be in use.


1 In .NET an object can still be garbage collected while an instance method is executing "in" the object, if the JIT compiler can prove that none of its variables will be read again. It's very confusing, and can cause very subtle bugs.



来源:https://stackoverflow.com/questions/8699755/does-the-object-which-is-the-entry-point-of-a-java-program-get-garbage-collected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!