views:

706

answers:

1

In google's Calendar app for Android OS, you will encounter this line in the onCreate method of CalendarActivity.

// Eliminate extra GCs during startup by setting the initial heap size to 4MB.
VMRuntime.getRuntime().setMinimumHeapSize(INITIAL_HEAP_SIZE)

Can someone explain why setting it to 4MB will eliminate GCs ? Thanks

+3  A: 

A JVM typically starts by allocating a relatively small heap. Then after each GC run it checks to see how much free heap memory there is. If the ratio of free heap to total heap is too small, the JVM will then add more memory to the heap (up to the maximum configured heap size).

A second relevant fact is that GC runs most efficiently when there is lots of memory to reclaim. Provided that you don't run into overall system resource limits (e.g. triggering paging or swapping), you get better application performance by running with a large heap than a small one.

Suppose that the application writer knows that the app most likely needs a given amount of heap (e.g. 4Mb) to run comfortably. By setting that size as the minimum heap size means that the JVM does not need to run the GC when the heap fills at (say) 1Mb, 2Mb and 3Mb. As a result, the JVM runs the garbage collector fewer times during application startup and normal running, the app starts up faster and the user sees fewer GC pauses.

Stephen C
Would a profiler help to estimate the initial bootup heap requirements ?
Jacques René Mesrine
It might help. But you still have to figure out (guess) how much extra memory to allow. I'd do this more directly; i.e. try different initial heap sizes and find a good compromise between performance and memory usage.
Stephen C