[英]Memory leak in Java. How to clear list?
I have found some list in my source code which has list.add()
but not list.remove()
. 我在源代码中找到了一些列表,其中包含
list.add()
但不是list.remove()
。 Is it causing a memory leak? 它是否导致内存泄漏? I tried
list.clear()
and list=null
but it seems to have no effect. 我尝试了
list.clear()
和list=null
但似乎没有效果。 What should be done to clear this list? 应该怎么做才能清除这个清单? Kindly explain... Thanks in advance.
请解释......先谢谢。
list.clear()
will clear all the reference from the list. list.clear()
将清除列表中的所有引用。 If they are not used by any other objects it will be cleared from memory by garbage collector
. 如果它们没有被任何其他对象使用,它将被
garbage collector
从内存中清除。 But clear
alone will not delete
the objects. 但单独
clear
不会delete
对象。 I think the problem is, some other objects are using the data so it is still there in the memory. 我认为问题是,其他一些对象正在使用数据,因此它仍然存在于内存中。
Post sample code to make us know what is the exact problem. 发布示例代码,让我们知道确切的问题是什么。
If you want to clear a list you can just call List.removeAll
. 如果要清除列表,只需调用
List.removeAll
。 Until objects are referenced somewhere they are not eligible to be garbage collected, so if a List.removeAll
does no effect, it means that the object that were in the list are still referenced somewhere else, for example in another collection or class. 在某些地方引用对象之前,它们不符合垃圾回收的条件,因此如果
List.removeAll
不起作用,则意味着列表中的对象仍然在其他地方引用,例如在另一个集合或类中。
How do you know that List.clear
/ List.removeAll
makes no effect ? 你怎么知道
List.clear
/ List.removeAll
是没有效果呢? It is not mandatory to remove each element that were added to a list manually. 不必删除手动添加到列表中的每个元素。 It is possible that a list runs out of scope and so is discarded.
列表可能超出范围,因此被丢弃。
{
Foo a = new Foo(1.0);
Foo b = new Foo(2.0);
{
List<Foo> foo = new ArrayList<Foo>();
foo.add(a); foo.add(b);
} // scope ends for foo, remove was not called but still
// the list is discarded, and the reference it holds to a and b too
}
So, to clear the list, just call List.removeAll
. 因此,要清除列表,只需调用
List.removeAll
。 If you want the objects that were in the list to be garbage collected, you have to make sure that they are no more referenced anywhere. 如果希望对列表中的对象进行垃圾回收,则必须确保它们不再在任何地方引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.