Language 3 of 10 · Topic 0.8

JVM Memory Architecture: Stack vs Heap & Garbage Collection (G1GC / ZGC)

1Concept

JVM memory consists of Stack (thread-local, frames for primitives & references) and Heap (shared, all objects created via new). Young Generation handles ephemeral objects; Old Generation holds long-lived instances. Tracing Garbage Collectors (G1GC, ZGC) automatically reclaim unreferenced memory.

2Architecture Diagram

+-------------------------------------------------------------+
|                          JVM MEMORY                         |
|  +-------------------+  +--------------------------------+  |
|  |   THREAD STACK    |  |          HEAP MEMORY           |  |
|  | - Primitive ints  |  |  +--------------------------+  |  |
|  | - Object Ref ptrs ───┼─►| Eden / Young Generation  |  |  |
|  | - Frame returns   |  |  +--------------------------+  |  |
|  +-------------------+  |  | Old / Tenured Generation |  |  |
|                         |  +--------------------------+  |  |
|                         +--------------------------------+  |
+-------------------------------------------------------------+

3Code Example

Stage 0 Language Foundations
public class MemoryModelDemo {
    static class UserSession {
        String sessionId;
        UserSession(String id) { this.sessionId = id; }
    }

    public static void main(String[] args) {
        // Stack stores primitive 'count' and reference 'session'
        int count = 100; // Stack
        UserSession session = new UserSession("AUTH_98765"); // Object on Heap

        System.out.println("Primitive on Stack: " + count);
        System.out.println("Heap Object Session ID: " + session.sessionId);

        // Make object eligible for Garbage Collection
        session = null;
        System.out.println("Session reference set to null (Heap object now eligible for GC).");
    }
}

4Expected Output

Primitive on Stack: 100
Heap Object Session ID: AUTH_98765
Session reference set to null (Heap object now eligible for GC).

5Key Takeaways

  • All Java class instances and arrays reside on the Heap.
  • Setting references to null or letting them fall out of scope makes objects eligible for GC.
  • ZGC provides sub-millisecond pause times on multi-terabyte heaps.