I was looking into ArrayList.clear() & found that it doesn't free the memory instead made that list null.
Why do you want to wait for GC to come & to free that memory (It could have done in clear method itself) when you can tell compiler manually that this particular ArrayList is no longer required.!!
Why do you want to give extra headache to GC Unnecessarily.
I know that System.gc() impacts the application performance since it runs garbage collection for the whole application.
Is there any way out to collect this particular ArrayList garbage instead of waiting GC to come to rescue in case of my server is having limited memory & list sizes are too too big.
Edit:-
This problem arises because I have initialized a ArrayList(500000) & lets assume my object size is around 1000bytes due to some pre-initalized variables but due to some exception in forming first object itself I need to return from that function with freeing that memory which I have allocated to that ArrayList.I want my application to consume as low as memory it can.
GC is the last resort for me.
Why do you want to wait for GC to come & to free that memory (It could have done in clear method itself)
No, it could not. The ArrayList
indeed won't be referencing the objects anymore, but the clear()
method doesn't know if they are still being referenced somewhere else, so that's why this is a job for the Garbage Collector.
Why do you want to wait for GC to come & to free that memory (It could
have done in clear method itself)
There's a big misunderstanding in the sentence above: all memory is freed by GC in Java, there is no way to manually free memory occupied by objects on the heap.
But to answer the question of why clear()
nulls out all the elements rather than just throwing away the old backing array, the simple answer is "because it was written that way".
The slightly longer answer is that you typically use clear()
before refilling the list with new elements, so throwing away the old array and allocating a new one (which then might need to be re-allocated several times to reach the same size as the earlier backing array) was seen as too wasteful.
If on the other hand you want to get rid of an ArrayList
for good, you don't need to call clear()
on it, you just null out any references to the list itself.