Asked in an interview. What happens if you specify max heap size (Xmx) greater than available RAM? I also wonder what happens if you specify min heap size (Xms) greater than available RAM?
When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
The amount of heap memory allocated to the Java virtual machine can impact performance. For example, if the Xmx value is too low (is set lower than the amount of live data in the JVM), it will force frequent garbage collections in order to free up the space (RAM).
You can improve performance by increasing your heap size or using a different garbage collector. In general, for long-running server applications, use the J2SE throughput collector on machines with multiple processors (-XX:+AggressiveHeap) and as large a heap as you can fit in the free memory of your machine.
To get rid of this error, the value of Xmx(maximum heap size) should always be greater than or equal to Xms(minimum heap size). Run the HelloWorld program with the value of Xms(minimum heap size) set to 1 gigabyte and Xmx(maximum heap size) set to 2 gigabytes.
The easiest way to find out is try it and see.
Edit: There are actually at least two answers to the question. Probably on a 64 bit system, as was mentioned, your app could grow and grow in memory usage and start thrashing. On a 32 bit system the story is a little different because the os is not able to give you that much heap space. For instance, if I run an app on Windows XP with 32 bit java with the command line option -Xmx2000m it will die with a message similar to the following:
Invalid maximum heap size: -Xmx2000m
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.
In Linux with 32 bit java, I get the following with -Xmx3000m:
Could not create the Java virtual machine.
Error occurred during initialization of VM
Could not reserve enough space for object heap
In Linux with 32 bit java, I get the following with -Xmx6000m
Invalid maximum heap size: -Xmx6000m
The specified size exceeds the maximum representable size.
Could not create the Java virtual machine.
Trying this with 64 bit Java, the JVM does allow you to allocate more memory than there is physical RAM, though if you ask for an extremely large amount of memory, the jvm will again fail with an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With