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 ?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.