byteBiter byteBiter - 4 months ago 14
Java Question

Memory usage does not change in my program

Given following codes which test the memory usage of a Java program:

List<Person> list = new ArrayList<Person>();
for (int i = 0; i <= 10000000; i++) {
list.add(new Person("Jim", "Knopf"));
}
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);


The output is always
286046
, no matter how I change the value of
i
. But large
i
means large memory usage, right? Any explanation?

Answer

The output is always 286046, no matter how I change the value of i. But large i means large memory usage, right? Any explanation?

When you gc() the list is has fallen out of scope (i.e. it is not used again) and is not retained. Try placing it in a static as this cannot be discarded.

Note: you will get more accurate memory accounting if you use -XX:-UseTLAB as this disables concurrent memory allocation makes accounting simpler.

Comments