</>

Technology

Core Java

Difficulty

Advanced

Interview Question

What is the Java Memory Model? Explain Stack, Heap, and Garbage Collection.

Answer

Java Memory Model

JVM Memory Areas

CODE
┌─────────────────────────────────────────────────────┐
│                     JVM Memory                       │
│                                                     │
│  ┌─────────────┐   ┌──────────────────────────────┐ │
│  │    STACK    │   │            HEAP               │ │
│  │─────────────│   │──────────────────────────────│ │
│  │ Thread-1   │   │  Young Generation             │ │
│  │  frame 1   │   │   ├── Eden Space               │ │
│  │  frame 2   │   │   ├── Survivor S0              │ │
│  │──────────── │   │   └── Survivor S1              │ │
│  │ Thread-2   │   │                               │ │
│  │  frame 1   │   │  Old Generation (Tenured)     │ │
│  └─────────────┘   └──────────────────────────────┘ │
│                                                     │
│  ┌──────────────────────────────────────────────┐   │
│  │          Method Area / Metaspace             │   │
│  │  Class bytecode, static vars, constants      │   │
│  └──────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────┘

Stack Memory

  • Stores method call frames and local variables
  • Each thread has its own stack
  • Memory is allocated/freed automatically (LIFO)
  • Fixed size — StackOverflowError if exhausted (infinite recursion)
Java
public static void main(String[] args) {
    int x = 10;          // local variable → stored in stack
    String name = "Alice"; // reference → stack; object → heap
    calculate(x);
}

public static int calculate(int a) {   // new stack frame created
    int result = a * 2;                // local → stack
    return result;
}   // frame popped — result removed from stack

Heap Memory

  • Stores all objects created with new
  • Shared across all threads
  • Managed by Garbage Collector
  • Divided into Young and Old Generations
Java
// Object stored in heap — reference variable in stack
Person p = new Person("Alice");  // "new Person()" → heap
                                  // variable p → stack (holds address)
p = null;  // p no longer references object
// Person object becomes eligible for GC

Garbage Collection (GC)

GC automatically reclaims memory occupied by objects with no references.

GC Process

CODE
1. Eden Space → new objects created here
2. Minor GC → survivors move to S0/S1
3. After several GC cycles → moved to Old Generation
4. Major/Full GC → cleans Old Generation (expensive)

Making Object Eligible for GC

Java
// 1. Set reference to null
Person p = new Person("Alice");
p = null;  // eligible for GC

// 2. Reassign reference
p = new Person("Bob");  // Alice object now unreachable

// 3. Object goes out of scope
{
    Person temp = new Person("Temp");
    // temp goes out of scope here — eligible for GC
}

Memory Leaks (Common in Java)

Java
// Static collections holding references indefinitely
public class SessionManager {
    private static List<Object> activeSessions = new ArrayList<>();

    public void addSession(Object session) {
        activeSessions.add(session); // never removed = memory leak
    }
}

// Fix: remove when done
public void removeSession(Object session) {
    activeSessions.remove(session);
}

JVM Flags for Memory

Bash
java -Xms256m        # Initial heap size 256MB
java -Xmx1024m       # Max heap size 1GB
java -Xss512k        # Thread stack size 512KB
java -XX:+UseG1GC    # Use G1 Garbage Collector

In Automation (OutOfMemoryError)

Java
// Common cause: storing all screenshots in memory
List<byte[]> screenshots = new ArrayList<>();

// In long test suites — screenshots accumulate → OutOfMemoryError
// Fix: process and discard immediately
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("target/" + testName + ".png"));
// Don't store in List

Follow AutomateQA

Related Topics