In the life-cycle of my application, I have to re-create an ArrayList that contains other ArrayLists of objects (reading them from storage). The ArrayList is always assigned to the same data member in a class, essentially leaving the older ArrayList-of-ArrayLists dangling (unreference-able or inaccessible).
My understanding is that, unlike in C++, this doesn't result in a memory leak because the system knows when an object becomes unreference-able and frees the memory when/as it sees fit.
Still, old habits are hard to overcome and I am almost instinctively drawn to "help" the system by doing some cleanup myself before re-creating that ArrayList-of-ArrayLists:
for (InnerArray aList : outerArray)
aList.clear();
outerArray.clear();
My questions:
It is redundant. You are not helping those objects get freed, because garbage collection will already determine them to be unreachable. You can't make them more unreachable than they already are. So, you waste a little bit of processing time on something that accomplishes nothing.
The main problem, though, is that you are confusing other developers who will be wondering why you're clearing that array. They may waste their time trying to figure out why you were doing that, if there's some hidden reason that they didn't see at first.
A similar problem that C++ developers tend to have with Java code is making finalizers; in Java you almost never want to do this, as finalizers add an additional cost to garbage collection and they aren't a reliable way to free resources because they may not get called for a long time, or ever.
P.S. I'm not sure about what I'm going to say now, but the clear()
function might remove elements from an ArrayList
just by making sure that you cannot access them anymore through the ArrayList
variable. Probably it won't 'destroy' them but it will just make them eligible for garbage collection. It would be nice to know how that function is implemented...
P.P.S. You might be tempted to invoke GC yourself, don't do it! See related question.
EDIT:
Here is the clear()
from ArrayList
:
public void clear()
{
if (size > 0)
{
modCount++;
// Allow for garbage collection.
Arrays.fill(data, 0, size, null);
size = 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With