局部变量上的垃圾收集
我是一名进入 Java 世界的 C++ 程序员.而且我无法摆脱不得不让 Java 垃圾收集器进行清理的糟糕感觉.
I'm a C++ programmer entering the world of Java. And I cannot get rid of the bad feeling of having to let the Java garbage collector do my cleaning.
例如,这段代码在 Java 中的表现如何?
How, for example, will this code behave in Java?
public void myFunction() {
myObject object = new myObject();
object.doSomething();
}
myFunction()退出时会不会删除局部变量对象?
Will the local variable object be deleted when myFunction() exits?
我必须在退出之前将 object 设置为 null,还是会超出范围并被 GC 删除?或者,在最坏的情况下,它会像在 C++ 中那样泄漏吗?
Do I have to set object to null before exiting, or will it be out of scope and be deleted by the GC? Or, at worst, will it leak like it would in C++?
推荐答案
它会在不再使用后的某个时间被垃圾回收.我相信在 Java 的当前实现中,它实际上会一直持续到方法结束,而 .NET 中的垃圾收集器更具侵略性.(我不知道即使在 Java 中是否也有任何保证.通常,您只希望局部变量在调试时持续超过其最后一次可能的读取.)
It will be garbage collected at some point after it's no longer used. I believe in current implementations of Java it will actually persist until the end of the method, whereas the garbage collector in .NET is more aggressive. (I don't know whether there are any guarantees even in Java. Normally you'd only want the local variable to persist beyond its last possible read when you're debugging.)
但是不,您不需要将变量设置为 null,这样做会损害可读性.
But no, you don't need to set the variable to null, and doing so would harm readability.
在方法退出后立即对象不太可能被垃圾回收;这取决于 GC 运行的时间......当然,如果有其他任何东西保留对对象的引用,那么它可能无论如何都没有资格进行垃圾收集.不要忘记变量的值只是一个引用,而不是对象本身.(这可能需要一段时间才能习惯来自 C++.)
It's unlikely that the object will garbage collected immediately after the method exits; it's up to when the GC runs... and of course if anything else holds onto a reference to the object, it may not be eligible for garbage collection anyway. Don't forget that the value of the variable is just a reference, not the object itself. (That may take a while to get used to coming from C++.)
相关文章