JVM Memory Areas in Java (Heap, Stack, Metaspace)
1. Introduction
The JVM (Java Virtual Machine) divides memory into different areas to efficiently manage program execution.
The most important memory areas are:
Heap Memory
Stack Memory
Metaspace (Method Area)
Understanding these is very important for performance tuning, debugging, and interviews.
2. JVM Memory Structure Overview
JVM Memory
|
|--- Heap
|--- Stack
|--- Metaspace
3. Heap Memory
Explanation
Heap is used to store objects and instance variables
Shared among all threads
Managed by Garbage Collector (GC)
Key Features
Stores all objects (
newkeyword)Divided into:
Young Generation
Old Generation
Slower access compared to stack
Example
class Student {
int id;
}
public class HeapExample {
public static void main(String[] args) {
Student s = new Student(); // stored in Heap
}
}
Explanation of Code
new Student()→ object created in HeapReference
sis stored in StackGC removes unused objects from Heap
4. Stack Memory
Explanation
Stack is used for method execution and local variables
Each thread has its own stack
Works in LIFO (Last In First Out) manner
Key Features
Stores:
Method calls
Local variables
References to objects
Very fast access
Automatically cleared after method execution
Example
public class StackExample {
public static void main(String[] args) {
int x = 10; // stored in Stack
method();
}
static void method() {
int y = 20; // stored in Stack
}
}
Explanation of Code
xandyare stored in StackWhen method ends → memory is automatically released
5. Metaspace (Method Area)
Explanation
Introduced in Java 8 (replaced PermGen)
Stores class metadata, such as:
Class structure
Method details
Static variables
Key Features
Not part of Heap
Uses native memory
Grows dynamically
Example
class Demo {
static int value = 100;
}
Explanation of Code
Class
Demometadata → stored in MetaspaceStatic variable
value→ stored in Metaspace
6. Key Differences Table
7. Real-Time Flow Example
public class MemoryFlow {
public static void main(String[] args) {
int a = 5; // Stack
Student s = new Student(); // Heap
}
}
class Student {
int id = 10; // Heap
}
Flow Explanation
main()→ Stack frame createda→ stored in Stacknew Student()→ object in HeapClass info → Metaspace
8. Common Issues
1. OutOfMemoryError (Heap)
Too many objects
Memory leak
2. StackOverflowError
Infinite recursion
void test() {
test(); // causes StackOverflowError
}
9. Summary
Heap → Stores objects (shared, GC managed)
Stack → Stores method calls & local variables (thread-specific)
Metaspace → Stores class metadata (native memory)
Understanding JVM memory helps in:
Writing optimized code
Debugging memory issues
Cracking interviews
Java Full Stack Developer Roadmap
To master JVM internals and advanced Java concepts:
👉 https://www.ashokit.in/java-full-stack-developer-roadmap
Promotional Content
Want to master JVM internals like Heap, Stack, and Memory Management?
.png)
Comments
Post a Comment