Search code examples
jvmsizeheap-memory

What is the optimal freeheap to totalheap ratio?


What is the optimal freeheap to totalheap ratio? At what values of this ratio should I consider increasing the heap size/ decreasing the heap size?


Solution

  • There is no single easy answer, let me give you two examples:

    Example 1 - Your program allocates 100M worth of memory at startup, and then does not allocate any memory what so ever for the rest of its run.

    In this case, you clearly want to have a heap size of 100M (Well, perhaps 101 or something, but you get the point...) to avoid wasting space.

    Example 2 - Your program allocates 10M of memory per second. None of the data is persisted longer than 1 second. (e.g. you are doing a calculation that requires a lot of temporary data, and will return a single integer when you are done...)

    Knowing the exact numbers is perhaps not so realistic, but it's an example.

    Since you have 10M of "live" data, you will have to have at least 10M heap. Other than that, you need to check how your garbage collector works. Simplified, the time a GC takes to complete is O(live set), that is, the amount of "dead" data does not really enter into it. With a constant live set size, your GC time is constant no matter your heap size. This leads to larger heap -> Better throughput.

    (Now, to really mess things up you add stuff like compaction of the heap and the image becomes even less clear...)

    Conclusion It's a simplified version of the matter, but the short answer is - It depends.