本文介绍了在循环中定义java对象,我是否需要使用null来释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(int i; i  {
MyObject obj = new MuObject();
obj.use();
}

我是否需要在开始的循环中说obj = null,或者结束释放该对象使用的内存,还是使用new将该对象发送给GC?我可以从内存使用的角度来看这个吗?

update:如果我有大对象和长循环,我应该将对象分配给null还是不是? -in-java.htmlrel =nofollow> http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html



如果对象无法从任何活动线程或任何静态引用到达,。循环结束后,您在循环内创建的对象没有任何指向它们的外部引用,并且有资格进行垃圾回收。



编辑:

如果您想查看内存使用情况,可以使用具有此功能的IDE来分析您的应用程序。例如,NetBeans有一个很好的界面,显示对象分配的实时内存使用情况。



编辑2:

因此,如果我有大对象和长循环,我应该将对象分配为空还是空?

不,您不需要这样做。一旦完成了循环的一次迭代,就不会有在该迭代中创建的任何对象的活动引用,因此无论您是长循环还是短循环都无关紧要。


If I have a loop and create a new object inside it

for ( int i ; i < 10 ; i++)
{
  MyObject obj = new MuObject();
   obj.use();
}

Do I need to say obj = null, inside the loop at the beginning or end to release memory used by that object , or by using "new" that object will be send to GC ? and can I see this in terms of memory usage ?

update : so in case I have big object and long loop , should I assign the object to null or no ?

解决方案

Check this: http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html

"An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static references". After the loop ends, the objects that you created inside the loop do not have any external references pointing to them and are eligible for garbage collection.

EDIT:
If you want to see memory usage, you can profile your application using an IDE that has such a feature. For example, NetBeans has a nice interface that shows live memory usage for object allocation.

EDIT 2:
"so in case I have big object and long loop , should I assign the object to null or no ?"
No, you do not need to do this. Once one iteration of the loop is complete, there are no active references to any objects created in that iteration so it does not matter that you have a long or short loop.

这篇关于在循环中定义java对象,我是否需要使用null来释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:03