本文介绍了作为Java程序入口点的对象是否会被垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有Sample类,并且有一个实例方法,则为instanceMethod.该类有一个主要方法,我可以在其中创建Sample本身的对象,并在不使用引用变量的情况下将其称为instanceMethod.

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.

像这样:

new Sample().instanceMethod();

new Sample().instanceMethod();

在主体内部.

由于该对象没有引用,垃圾收集器会收集它吗?

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

推荐答案

在Java 中,我不认为在执行instanceMethod()时可以收集对象.在main方法的堆栈框架中,至少在逻辑上 是对该对象的引用(JIT编译器可以忽略它).您没有将其分配给变量的事实并不会很大地影响字节码.

In Java, 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.

当然,当instanceMethod()完成时,对象可能可以进行垃圾回收-但可能不是.例如,instanceMethod()可能在静态变量中存储对this的引用.

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.

基本上,不应该将它们挂在错综复杂的极端情况下-仅依靠GC收集无法再以任何方式到达的对象,而不是收集可能仍在使用的对象.

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.

在.NET中,如果JIT编译器可以证明没有对象对象 ,则当实例方法在对象内部"执行该对象时,该对象仍可以被垃圾回收变量将再次读取.这非常令人困惑,并且可能会导致非常细微的错误.

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.

这篇关于作为Java程序入口点的对象是否会被垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:52