Wednesday, February 24, 2010

java.lang.OutOfMemory exception.

I was attempting to run a jar file and then i bumped into java.lang.OutOfMemory exception.

Lets start with some background. As you know every program needs certain amount of memory in heap to run. There are two values known as initial heap size and maximum heal size. In Java 5.0 the initial heap size is set to 1/64th of available physical memory on the machine and the maximum heap size is set to 1/4th of available physical memory.


Now in case you run a program say using java command and run into java.lang.OutOfMemory this simply means that your program needs more heap memory than that is available and you can do that by overriding the initial heap size and maximum heap size. To overiride the initial heap size to say 150 MB you can use java -Xms150000K and to overiride the maximum heap size to say 250 MB you can use java -Xmx250000K. Remember maximum heap size must be set greater than initial heap size or else you see
Error occurred during initialization of VM
Incompatible initial and maximum heap sizes specified

So remember the options Xms and Xmx, these are called non-standard options. For a complete list of non-standard options run java -X

So suppose am running a jar file which had run into an java.lang.OutOfMemory exception. Then i could re-run it as follows
java -Xms150000K -Xmx250000K -jar myJar.jar


Unfortunately, the only way to determine the amount of heap that your program is running is via

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an java.lang.OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

Hence one has to keep changing the heap values and run the program until you stop seeing java.lang.OutOfMemoryException. I was able to run my program with initial heap 150MB and and maximum heap of 250MB.

No comments:

Post a Comment

Twitter Updates

    follow me on Twitter