Java error – Could not reserve enough space for object heap

December 20, 2009 by Alex
Filed under: Java, Web programming 

Question: I have a Linux web server with JRE and has got problems trying to run a Java APP from the shell. It seems that web server limits the memory I can allocate. Error messages:

Error occurred during initialization of VM
Could not reserve enough space for object heap

Shell code:

java -Xmx1950m -cp helloworld.jar

What’s wrong? Any ideas?

Answer:

Some possible reasons:

1) This error means there is not enough memory allocated to the Java Virtual Machine (JVM)

2) The user limits are set too low in /etc/security/limits.conf or /etc/profile/.bash_profile in Linux

3) The allocated memory heap to the JVM is greater than 1.5GB and the OS is only 32 bit.

Our natural reaction is “it must be a JVM heap size issue, when the max size is too small“, and we usually start to increase the memory allocation. It may be a totally wrong direction…

Try to lower the memory demand to the value you really need to run your app:

1
java -Xmx512m -jar "/home/myapp/myapp.jar"

Why? The memory, JVM allocates to your application, affects the number of threads that can be allocated to your application, so hence the error.

This formula gives a decent estimate for the number of threads you can create:
(MaxProcessMemory – JVMMemory – ReservedOsMemory) / (ThreadStackSize) = Number of threads

Do not set high JVM memory (such as -Xmx1950m) value just because you want to be sure to get enough allocated memory. The JVM will not be able to run threads.