Java的垃圾收集器会继续并处理在循环中声明的变量吗? [英] Will Java's garbage collector go ahead and take care of variables declared within loops?

查看:666
本文介绍了Java的垃圾收集器会继续并处理在循环中声明的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

pre $ for(int i; i!= 100; i ++){
ArrayList<串GT; myList = buildList();
// ...更多在这里工作
}

我必须在我的循环结束时将myList设置为null来让GC回收它用于myList的内存?

将自动清除不再在范围内的任何变量。

块中声明的变量(例如for循环)只会在该块内的范围内。一旦代码退出该块,GC将删除它。只要循环的迭代结束,就会发生这种情况,所以只要循环的每次迭代完成,列表就可以进行垃圾回收。



变量的作用域也是为什么 i 在您的示例循环后无效。



请注意,只有您仅在循环内使用该变量。如果你将它传递给另一个引用它的方法,你的变量将不会被垃圾收集。


If I have:

for (int i; i != 100; i++) {
    ArrayList<String> myList = buildList();
    //... more work here
}

Do I have to set myList to null at the end of my loop to get the GC to reclaim the memory it uses for myList?

解决方案

The GC will automatically clean up any variables that are no longer in scope.

A variable declared within a block, such as a for loop, will only be in scope within that block. Once the code has exited the block, the GC will remove it. This happens as soon as an iteration of the loop ends, so the list becomes eligible for garbage collection as soon as each iteration of the loop finishes.

The scope of a variable is also why i would not be valid after your example loop.

Note that this only is the case if you use the variable only within the loop. If you pass it to another method that keeps a reference to it, your variable will not be garbage collected.

这篇关于Java的垃圾收集器会继续并处理在循环中声明的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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