Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Java Heap Space Exception in java

I'm reading data from IO having huge volume of data and I need to store the data in key value pair in Map or properties file, then only I can use that data for generating reports. But when I am storing this huge data in Map or Properties file, Heap Memory Exception is coming.Instead, if I am using SQLLite its taking very huge time to retrieve that. Is there any different way available to achieve this.Please suggest.

like image 397
Ananta Ch. Swain Avatar asked Mar 24 '26 04:03

Ananta Ch. Swain


1 Answers

Java Heap Space Important Points

  1. Java Heap Memory is part of memory allocated to JVM by Operating System.

  2. Whenever we create objects they are created inside Heap in Java.

  3. Java Heap space is divided into three regions or generation for sake of garbage collection called New Generation, Old or tenured Generation or Perm Space. Permanent generation is garbage collected during full gc in hotspot JVM.

  4. You can increase or change size of Java Heap space by using JVM command line option -Xms, -Xmx and -Xmn. don't forget to add word "M" or "G" after specifying size to indicate Mega or Gig. For example you can set java heap size to 258MB by executing following command java -Xmx256m javaClassName (your program class name).

  5. You can use either JConsole or Runtime.maxMemory(), Runtime.totalMemory(), Runtime.freeMemory() to query about Heap size programmatic in Java.

  6. You can use command "jmap" to take Heap dump in Java and "jhat" to analyze that heap dump.

  7. Java Heap space is different than Stack which is used to store call hierarchy and local variables.

  8. Java Garbage collector is responsible for reclaiming memory from dead object and returning to Java Heap space.

  9. Don’t panic when you get java.lang.OutOfMemoryError, sometimes it’s just matter of increasing heap size but if it’s recurrent then look for memory leak in Java.

  10. Use Profiler and Heap dump Analyzer tool to understand Java Heap space and how much memory is allocated to each object.

Reference link for more details:

https://docs.oracle.com/cd/E19159-01/819-3681/abeii/index.html

https://docs.oracle.com/cd/E40520_01/integrator.311/integratoretl_users/src/ti_troubleshoot_memory_errors.html

like image 172
Roshan Jain Avatar answered Mar 25 '26 17:03

Roshan Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!