← Back to Module 4

Memory Storage

Heap Memory Organization

Memory Generations

Object Lifecycle

// 1. Object creation in Eden Space
String str = new String("Hello");

// 2. Object survives minor GC
// Moved to Survivor Space

// 3. Object survives multiple GCs
// Moved to Old Generation

// 4. Object becomes unreachable
str = null;

// 5. Object collected by GC

Stack Memory Organization

Stack Frame Structure

Stack Frame Example

public class StackExample {
    public static void main(String[] args) {
        // Local variables stored in stack frame
        int x = 10;
        int y = 20;
        
        // Method call creates new stack frame
        int result = add(x, y);
    }
    
    public static int add(int a, int b) {
        // New stack frame created
        return a + b;
    }
}

Method Area Organization

Class Data Storage

Memory Allocation Strategies

Object Allocation

public class ObjectAllocation {
    // Static field - stored in method area
    private static int staticField;
    
    // Instance field - stored in heap
    private int instanceField;
    
    public void method() {
        // Local variable - stored in stack
        int localVar = 42;
        
        // Object - stored in heap
        String str = new String("Hello");
        
        // Array - stored in heap
        int[] array = new int[10];
    }
}

Memory Layout

// Object header (16 bytes on 64-bit JVM)
// Mark word (8 bytes)
// Class pointer (8 bytes)

// Instance data
// - Primitive types: their size
// - References: 4 bytes (32-bit) or 8 bytes (64-bit)

// Padding (to align to 8 bytes)

Memory Tuning

JVM Parameters

// Heap size settings
-Xms2g -Xmx4g

// Young generation settings
-XX:NewSize=1g -XX:MaxNewSize=2g

// Survivor ratio
-XX:SurvivorRatio=8

// Garbage collector settings
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200

Memory Monitoring

// Enable GC logging
-verbose:gc
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-Xloggc:gc.log

// Enable heap dump on OOM
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/path/to/dump

Video Content