Saturday, June 4, 2011

Exception in thread main java.lang.OutOfMemoryError: Java heap space in tomcat

How to solve java.lang.out of memory error? Why do I get  java.lang.out of memory error? "Exception in thread "main" java.lang.OutOfMemoryError: Java heap space"
While we develop web application in java and deploy into Apache Tomcat server, if we are playing with huge data then we might be getting java.lang.OutOfMemoryError most of time.
This is error, and can't be caught at development time, so at runtime we will get this error at any time when we try to create lots of variable more than available.
People might be thinking that their machine have memory of 2GB, then why are they getting memory error? You might have small confusion, if you have 2GB it does not mean you server is using whole 2GB ram for your application. By default Apache Tomcat use just 64K from whole memory of the system.

Then how to fix out of lang memory problem? How to increase heap size memory for tomcat server?
Here is the solution for java.lang.OutOfMemoryError Java heap space error:

1: Increase memory for apache tomcat server from the system:
Example to increase memory for tomcat server:
Go to tomcat main folder\bin, open catilina.bat file, add following line to set minimum 128 M to maximum 256 M
set CATALINA_OPTS=-Xms128M -Xmx256M -Djava.awt.headless=true

2: Refractor code and use StringBuilder instead of String.
Basically, writing lots of code in same method is not good practice. Declaring lots of String variables and appending text to same String variable use much more memory.
As we know when we append any text to same String variable, it actually create new variable in memory, you can look into the String documentation. So if you use StringBuilder, it won't create new variable when you append text to same variable, it append text to same variable in the memory instead.





No comments:

Post a Comment