This article will explain the Memory in Java, the different parts & which is responsible for what? It will go through Stack, Heap, Young, Old Generation & Perm Gen.
I believe it’s really important for all Java developers to understand the memory management.
- Stack memory is used for the thread execution, it contains the primitive variables & references to the objects created in Heap.
- It is LIFO (Last In First Out). Whenever a method is called, a new block is created in the stack for this method.
- Once a method ends it’s popped up from the stack and the next block is to be executed.
- Stack memory is smaller compared to the Heap size.
- It is used to allocate any object “Using new keyword”.
- The garbage collection goes through the Heap space to free the memory used by any object that no longer has any reference to it.
- If an object is created, it is located in the heap with all its variables. So that it can persist after the function call returns.
Young Generation (Heap):
- All the new objects are created in the young generation. When it’s filled a Minor Garbage Collection is performed, the objects that are survivors (not removed by GC) will be moved to the Old Generation.
- The YG is divided into three parts, Eden Memory & two Survivor Memory.
- The steps of filling & clearing the YG memory:
- All the new objects are created in Eden Memory space.
- Once the Eden Memory is filled, a minor GC is performed and move all the survivor objects to one of Survivor Memory spaces.
- After a defined threshold defined by the JVM (maybe a couple of rounds of minor GC), the objects in the Survivor Memory will be moved to the Old Generation.
Old Generation (Tenured Gen – Heap):
- Old Generation space contains the objects that survived multiple rounds of Minor GC.
- Major Garbage Collection is performed when the OG is full, and this Major GC usually takes more time.
- It’s also known as Tenured Generation.
Permanent Generation (Perm Gen – Not in Heap):
- It contains the application metadata required by the JVM to describe the classes & methods in your application.
- Also the Perm Gen is not a part of the Heap Memory.
- It’s populated by the JVM at run-time when the program starts.
- Setting those variables -XX:MaxPermSize & -XX:PermSize will helps in solving the “OutOfMemoryError: PermGen space” exception.