Given a java memory configuration like the following
-Xmx2048m -Xms512m
What would be the behaviour of the VM when memory usage increases past 512m? Is there a particular algorithm that it follows? ie. Does it go straight to the max, does it double, does it go in increments, or does it only allocate as it needs memory? How expensive an operation is it?
I’m looking specifically at the Oracle/Sun JVM, version 1.6. I assume this is documented on the Oracle website somewhere, but I’m having trouble finding it.
It’s the garbage collector’s job to decide when resizing is necessary, so it is determined by the GC parameter ‘MinFreeHeapRatio.’ If the GC needs more space, it will grow to a size where the % of heap specified by that value is available.
A typical value on a modern platform is 40ish, so if you start at 512MB and have less than 40% free, meaning you exceeded ~308MB, it will increase until 40% is free again. So say after collection there are still 400MB worth of live objects, your heap will go up to ~667MB. (Yes it is named ratio but expects a % value as argument… search me!)
Note this is a bit inexact, the garbage collector is “generational” and actually can resize individual generations, but it also has forced ratios between generations sizes and if your objects are distributed between long lived and short lived in roughly the way it estimates, it works out pretty well for back of the envelope.
This applies to defaults in Java 6. If you use custom garbage collector config it may be different. You can read about that here: http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html#generation_sizing.total_heap
(The “expense” of the operation kind of depends on the operating system and what else is going on. If the system is loaded down and the OS has to do some swapping to make a contiguous block of memory for you, then it could be very expensive!)