7

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?

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
Jacques René Mesrine
  • 46,127
  • 27
  • 66
  • 104

1 Answers1

16

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
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    Would a profiler help to estimate the initial bootup heap requirements ? – Jacques René Mesrine Oct 05 '09 at 10:06
  • 1
    Not directly. Suppose that you run the profiler on a snapshot taken when the application has "booted". This tells you how objects exist at that point, but not 1) what the maximum working set was *during* bootstrapping, or 2) how much extra memory will be consumed when the application starts doing things. In short, the working set size after bootstrap could be a poor estimate. – Stephen C Mar 06 '11 at 05:52