0

I have written this following code to check the garbage collection and expecting that garbage collection will not occur since I'm maintaining the reference of objects.

import java.util.ArrayList;

public class HeapConsumer
{
public static void main(String args[])
{
ArrayList<Integer> list = new ArrayList<Integer>();
int i = 0;
while(true)
{
list.add(new Integer(i));
System.out.println(i);
i++;
try
{
Thread.sleep(500);
}catch(InterruptedException e){}
}
}
}

But when watching the memory graph in JConsole it was sawtooth like graph indicating garbage collection.Will there any garbage collection for this code ?

Edited by peter_budo: Keep It Clear - Do use code tags when posting any code

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

Suggest you have a look at the source code for ArrayList. My guess is that it allocates an array of some default size and adds elements until that's full, at which point it copies the existing data to a new larger array then releases the old one - thus giving a sawtooth to the memory usage.
You could check that by creating the ArrayList with a very large initial capacity, in which case you should see an initial hike in memory followed by nothing.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.