简体   繁体   中英

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() . Is it causing a memory leak? I tried list.clear() and list=null but it seems to have no effect. What should be done to clear this list? Kindly explain... Thanks in advance.

list.clear() will clear all the reference from the list. If they are not used by any other objects it will be cleared from memory by garbage collector . But clear alone will not delete the objects. 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 . 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.

How do you know that List.clear / List.removeAll makes no effect ? 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM