The Heap memory in JVM is the runtime memory where all Java objects and instance variables are stored. It is the largest part of the JVM memory and is shared among all threads.
How Heap Memory is Used in JVM
- Object Allocation:
- Whenever
new
is used to create an object, memory is allocated in the Heap. - Example
- Whenever
class Car {
String model;
}
Car myCar = new Car(); // Allocated in Heap
Garbage Collection (GC):
- JVM automatically reclaims memory of unused objects through Garbage Collection (GC).
- Objects without references become eligible for GC.
Divided into Different Generations (Memory Segments):
- The Heap is divided into:
- Young Generation (Short-lived objects)
- Old Generation (Tenured Space) (Long-lived objects)
- Metaspace (Class metadata storage)
Heap Memory Structure
1️⃣ Young Generation (New Objects)
- Stores newly created objects.
- It has three parts:
- Eden Space – New objects are first allocated here.
- Survivor Space S0 & S1 – Objects that survive minor GC move between these two spaces.
- Garbage Collection: Minor GC runs frequently here.
2️⃣ Old Generation (Long-Lived Objects)
- Objects that survive multiple GC cycles move here.
- GC here is less frequent but more expensive (Major GC or Full GC).
3️⃣ Metaspace (Class Metadata)
- Stores class-related information (replacing PermGen in Java 8+).
- Dynamically grows as needed.
How JVM Manages Heap Memory Efficiently
- JVM tunes heap memory dynamically.
- Uses GC algorithms (like G1GC, Parallel GC, ZGC) to manage memory efficiently.
- Developers can configure Heap Size:
-Xms
→ Initial Heap Size-Xmx
→ Maximum Heap Size
Example:
java -Xms512m -Xmx2g MyApp
Heap Memory vs Stack Memory
Feature | Heap Memory | Stack Memory |
---|---|---|
Stores | Objects, instance variables | Local variables, method calls |
Scope | Shared among threads | Each thread has its own stack |
Lifetime | Until Garbage Collection | Until method execution ends |
Performance | Slower due to GC | Faster (direct access) |
Would you like to explore Garbage Collection tuning or Heap memory optimization strategies? 🚀