← Back to Module 4
Memory Storage
Heap Memory Organization
Memory Generations
- Young Generation:
- Eden Space
- Survivor Spaces (S0 and S1)
- Old Generation:
- Permanent Generation:
- Class metadata
- Interned strings
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
- Local Variables: Method parameters and local variables
- Operand Stack: Working memory for computations
- Frame Data: Exception table and method return data
- Constant Pool Reference: Reference to runtime constant pool
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
- Class Information:
- Class name
- Superclass
- Interfaces
- Access modifiers
- Method Information:
- Method names
- Return types
- Parameter types
- Method bytecode
- Static Variables:
- Class-level variables
- Constants
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