← Back to Module 4
Introduction to Memory
JVM Memory Architecture
The Java Virtual Machine (JVM) manages memory automatically, providing a robust and efficient memory management system. The JVM memory architecture consists of several key components:
- Heap: The runtime data area from which memory for all class instances and arrays is allocated
- Stack: Stores local variables and partial results
- Method Area: Stores class-level data and method code
- Program Counter (PC) Register: Contains the address of the JVM instruction currently being executed
- Native Method Stack: Contains native method information
Memory Management in Java
Automatic Memory Management
Java provides automatic memory management through garbage collection, which:
- Identifies and removes unused objects
- Prevents memory leaks
- Manages memory allocation and deallocation
- Optimizes memory usage
Memory Allocation
// Object allocation
String str = new String("Hello"); // Allocated on heap
int number = 42; // Allocated on stack
// Array allocation
int[] array = new int[1000]; // Allocated on heap
double[][] matrix = new double[10][10]; // Allocated on heap
Memory Types
Stack Memory
- Stores primitive types and object references
- LIFO (Last In First Out) structure
- Thread-specific
- Fixed size
Heap Memory
- Stores objects and arrays
- Shared among all threads
- Dynamic size
- Managed by garbage collector
Method Area
- Stores class-level data
- Contains method code
- Shared among all threads
- Part of the heap in some JVM implementations
Memory Errors
Common Memory Errors
// StackOverflowError
public void recursiveMethod() {
recursiveMethod(); // Infinite recursion
}
// OutOfMemoryError
public void createLargeArray() {
int[] array = new int[Integer.MAX_VALUE]; // Too large array
}
// Memory Leak Example
public class MemoryLeak {
private static List<Object> list = new ArrayList<>();
public void addObject(Object obj) {
list.add(obj); // Objects never removed
}
}
Error Prevention
- Use appropriate data structures
- Implement proper resource cleanup
- Monitor memory usage
- Use profiling tools
Memory Monitoring
JVM Parameters
// Set initial heap size
-Xms512m
// Set maximum heap size
-Xmx1024m
// Enable garbage collection logging
-verbose:gc
// Set garbage collector
-XX:+UseG1GC
Monitoring Tools
- JConsole
- VisualVM
- Java Flight Recorder
- Eclipse Memory Analyzer (MAT)