垃圾收集本地变量 [英] Garbage collection on a local variable

查看:83
本文介绍了垃圾收集本地变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名进入Java世界的C ++程序员。我不能摆脱让Java垃圾收集器清理我的不好感觉。



例如,这段代码如何在Java中运行?

  public void myFunction(){
myObject object = new myObject();
object.doSomething();

当myFunction()退出时,局部变量对象是否会被删除?



在退出之前是否必须将对象设置为null,还是会超出范围并被GC删除?或者,最糟糕的情况是,它会像C ++一样泄漏吗?

它会在某个时间点被垃圾收集在不再使用之后。我相信在Java的当前实现中,它实际上会持续到方法结束,而.NET中的垃圾收集器更具侵略性。 (即使在Java中,我也不知道是否有任何保证,通常情况下,你只希望本地变量在调试时保持超出最后可能的读取范围。)



但是,不需要将变量设置为null,这样做会损害可读性。



不太可能在方法退出后,该对象将立即被垃圾收集 。这取决于GC运行的时间......当然,如果有其他任何东西持有对该对象的引用,它可能无论如何都不符合垃圾回收的条件。不要忘记,变量的值只是一个引用,而不是对象本身。 (这可能需要一段时间才能习惯来自C ++。)


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.

How, for example, will this code behave in Java?

public void myFunction() {
    myObject object = new myObject();
    object.doSomething();
}

Will the local variable object be deleted when myFunction() exits?

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++?

解决方案

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.)

But no, you don't need to set the variable to null, and doing so would harm readability.

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++.)

这篇关于垃圾收集本地变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆