Does the object which is the entry point of a Java

2019-07-24 23:30发布

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条回答
别忘想泡老子
2楼-- · 2019-07-25 00:04

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.

查看更多
登录 后发表回答