A Guide to java memory parameters

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Filament.io 0 Flares ×

Java Memory

Java has two memory areas namely the heap memory and non heap memory. There are also many other memory areas but these are sub sections within heap or non heap memory.

Heap memory is where Java stores the objects and arrays. This memory is shared across all threads operating in a JVM instance. Hence care should be taken when working with the same objects or arrays from multiple threads.

One common issue that many developers have to address is that of applications that terminate with java.lang.OutOfMemoryError.  This means that there is not sufficient memory in the heap to accomodate the object. This doesn’t mean that there is a memory leak in your program. But that is a possibility if  the program is not well written. Most often it is related to memory configuration and not leak. When you have allocated insufficient heap memory than what your program naturally needs it can result in OutOfMemory error. The first thing in such a situation is to examine the error message and see what area in heap is causing the OutOfMemoryError.

If the error message contains the text Java heap space, it indicates that an object could not be allocated in the heap. The issue may be just a configuration problem. You can correct this error by increasing the Heap Size using the -Xmx JVM option.

For instance,

java -Xmx128m HelloWorld sets the maximum heap to 128 Mega Bytes. You can also set the initial heap size using -Xms option.

Some times the error might include the text PermGen space . This indicates that the permanent generation is full. This is the area of the heap where the JVM stores its metadata. If an application loads a large number of classes, then the permanent generation may need to be increased.

This is done using the JVM option –XX:MaxPermSize=n, where n specifies the size.

Example java –XX:MaxPermSize=128m HelloWorld

In very rare cases, you might encounter a string Requested array size exceeds VM limit in the error message. This means your program tried to allocate and array whose size is greater than the heap size. The cause is usually due to insufficient heap size or a bug in the program.

Java memory parameters – Quick Recap

-Xmx128m [ Sets a max heap size of 128 Mega Bytes ]

-Xms64m [ Sets initial heap size to 64 Mega Bytes ]

–XX:MaxPermSize=128m [Sets Perm Gen Space to 128 Mega Bytes ]