← 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:

Memory Management in Java

Automatic Memory Management

Java provides automatic memory management through garbage collection, which:

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

Heap Memory

Method Area

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

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

Video Content