Friday, April 10, 2015

Heap Space in Java

When a Java program started 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.

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 HelloWord.

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

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

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

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

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



No comments: