This document holds the summary of memory management concepts in JVM (Java Virtual Machine) that every software engineer should be aware of while designing/coding in Java.
Stack : Small when compared to heap memory and stores local variables and references to the objects in Heap.
- Each thread has its own Stack.
- Shorter life span
- Data from Stack is removed as soon as close braces ( } ) is encountered.
- Primitive types are saved in Stack.
- If a method pushed 10 elements to the Stack, all the 10 will be removed upon encountering closing braces.
Heap : This should be your main focus while designing/coding/debugging/testing the application.
- Long term memory.
- All objects are stored in the heap and references of those are saved on Stack.
- JDK provides jvisualvm application to analyse heap memory.
- In modern JVM heap is split into 2 types.
- Old Generation
- Young Generation - which in turn split into 3 types.
- Survivor 0
- Survivor 1
Heap Memory to the Naked Eye
- Above image shows the heap memory of a spring boot application where the maximum heap size set to 50mb.
- For maven spring boot application.
- set MAVEN_OPTS="-Xmx50m"
- mvn spring-boot:run
- Look how 50Mb is split among old, Eden, Survivor 1 and 2 memory.
- Old Generation – 33.5 MB
- Survivor 1 & 2 – 2.5 MB each
- Eden – 15 MB
- Objects are first allocated in Eden memory location if they survive the garbage collection, they are moved to survivor memory, then to Old generation. An object, in general, is moved to Old generation if it survives garbage collection more than eight times.
- Garbage collector decides which memory should be cleared, i.e. Eden memory/ Old Gen memory based on the amount of memory it needs. In general, GC mostly clears the young memory and sometimes rarely old Gen.
Explore jvisualvm tool of JDK to monitor CPU, memory, threads, instances and get the heap dump. Use eclipse memory analyser to see which class instances take up huge memory and which member variable is responsible for the memory leak.