Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List.clear() vs. List = null [duplicate]

I'm running my application under a profiler and the memory usage is much higher than I expect, where objects are still in existence after they are no longer needed. Most of them are in lists where the list object has gone out of context.

Does it take the garbage collector longer to free up objects that are sitting in a list, even if the list itself is no longer referenced? If so, will they free up sooner if I call clear() on the list before it goes out of context?

thanks - dave

like image 852
David Thielen Avatar asked Mar 25 '14 12:03

David Thielen


3 Answers

In terms of the garbage collection mechanics, you are asking whether GC roots have any priority over all other, transitively reachable objects in being detected as unreachable. Given the way the mark-sweep algorithms work, there is no difference between these two. All such garbage objects will be marked in the same pass and the internal reachability of an object from within an unreachable object has no impact on this.

Finding a lot of unreachable objects still not being reclaimed is nothing unusual and it is actually to the benefit of overall application performance: only when memory allocation fails will the GC run. If you are worried about the size of your heap, then simply reduce the maximum heap size. This will cause more frequent garbage collection.

like image 148
Marko Topolnik Avatar answered Oct 04 '22 22:10

Marko Topolnik


If we take an ArrayList as an example, the clear() method does this:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

Basically, if a List and elements of the List are not referenced anywhere else in the code there is really no need to call clear() (or at least you do not gain anything by doing so). You also do not need to assign null to the List variable because it will be garbage collected at some point after it falls out of scope (again, if the list itself is not referenced anywhere else).

Check out how "mark and sweep" garbage collection algorithm works: http://wiki.c2.com/?MarkAndSweep

like image 38
darijan Avatar answered Oct 04 '22 21:10

darijan


Yes. clear will remove references to objects in the list, at least the ArrayList implementation of list will do so. However if your whole List object is going out of scope anyways, you don't gain anything.

like image 33
RokL Avatar answered Oct 04 '22 22:10

RokL