Sunday, May 22, 2011

Java Heap Space Error

What is Heap Space?
When a Java program starts, Java Virtual Machine gets some memory from
Operating System.Java Virtual Machine or JVM uses this memory for all
its need and part of this memory is call java heap memory. Heap in Java
generally located at bottom of address space and move upwards.
whenever we create object using new operator or by any another means object
is allocated memory from Heap and When object dies or garbage collected
,memory goes back to Heap space in Java.

Reason for the Error?
Java programs executes in JVM uses Heap of memory to manage the data.
If your Java program requires a large amount of memory,
it is possible that the virtual machine will begin to throw OutOfMemoryError
instances when attempting to instantiate an object.

How to tune JVM Heap Space?
We can tune JVM through two parameters named as -Xms and -Xmx.
-Xms : initial heap space
-Xmx : Maximum heap size

Setting Heap Size in Apache Ant.
To increase heap size in Apache Ant ,Set environment variable
ANT_OPTS. The ant.bat file reads this environment variable at runtime.

set ANT_OPTS="-Xms512m -Xmx512m" (Windows)
directly set the environment variable as:
variable name : ANT_OPTS
variable value : -Xms512m -Xmx512m

export ANT_OPTS="-Xms512m -Xmx512m" (ksh/bash)

setenv ANT_OPTS "-Xms512m -Xmx512m" (tcsh/csh)

Setting Heap Size in Apache Tomcat.
The heap size of Tomcat can be set through the environment variable

set CATALINA_OPTS="-Xms512m -Xmx512m" (Windows)
export CATALINA_OPTS="-Xms512m -Xmx512m" (ksh/bash)
setenv CATALINA_OPTS "-Xms512m -Xmx512m" (tcsh/csh)

How to set java heap size in JBoss.
To set heap size in JBoss server, just edit $JBOSS_HOME/bin/run.conf.
Now change the line with JAVA_OPTS as specified below:

JAVA_OPTS="-server -Xms512m -Xmx512m"

How to set java heap size in Eclipse.
In Eclipse we can change the heap size in two ways:

1. Edit eclipse-home/eclipse.ini as specified below and then start Eclipse.

2. Or, you can just run eclipse command with additional options at the very end.
Anything after -vmargs will be treated as JVM options and passed directly to the JVM.
JVM options specified in the command line this way will always override those in eclipse.ini.
For example,

eclipse -vmargs -Xms128m -Xmx256m

How to set java heap size in NetBeans.
Just edit the file netbeans-install/etc/netbeans.conf :
netbeans_default_options="-J-Xms512m -J-Xmx512m -J-XX:PermSi