Reputation: 2886
I was trying to get to know how memory-management work after I got a JVM-memory-allocation-crash in a MPI program of mine. In order to do this, I added the lines as can be seen underneath.
public static void main(String[] args) throws MPIException {
System.out.println("memory upon initialisation: " + (Runtime.getRuntime().totalMemory() >> 20) + "MB");
//run some with some loops and a lot of variables...
System.out.println("memory when finished: " + (Runtime.getRuntime().totalMemory() >> 20) + "MB");
}
I ran this code and could see how the heap size had increased, but when I added the line System.gc();
to my code, the heap size didn't expand anymore.
My question thus is: why does JVM seem to prefer expanding the heap over doing some garbage collection? I would expect the JVM to rather first try garbage collection before further memory allocation.
Thanks in advance
Upvotes: 1
Views: 714
Reputation: 200296
JVM assumes that you are OK with it allocating as much heap as you have allowed with -Xmx
. More heap headroom means greater GC throughput and less frequent GC pauses. It is up to you to decide how much RAM you are willing to invest in helping your JVM perform well. At least that's the default reasoning; you may influence JVM's choice with a large arsenal of configurable options.
Upvotes: 2