Comprehensive Guide to JVM Memory Areas, Garbage Collection, and Related Concepts

This article provides an in‑depth overview of the JVM runtime data structures, memory regions, garbage‑collection algorithms, GC roots, reference types, stop‑the‑world pauses, OopMap, safe points, stack‑overflow handling, class‑loading mechanisms, the parent‑delegation model, object stack allocation, and object layout, offering practical insights for Java developers preparing for interviews.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Comprehensive Guide to JVM Memory Areas, Garbage Collection, and Related Concepts

1. JVM Memory Areas

The JVM divides runtime memory into several regions, each with distinct responsibilities and lifetimes. The Program Counter (thread‑private), the Java Virtual Machine Stack (thread‑private), the Native Method Stack, the Heap (shared among all threads), the Method Area (shared, stores class metadata, constants, static variables), and Direct Memory (off‑heap, used by NIO and often paired with phantom references).

2. How Garbage Objects Are Found

Two main approaches are described:

Reference‑Counting Algorithm : each object maintains a counter that increments on new references and decrements when references disappear; an object becomes garbage when its counter reaches zero, though it cannot reclaim cyclic references.

Root‑Reachability Algorithm : the JVM defines a set of GC Roots (e.g., thread stacks, static fields, JNI handles, internal VM references). Starting from these roots, the collector traverses the object graph; any object not reachable from a root is considered garbage.

3. Types of GC Roots

GC Roots are divided into fixed and temporary categories. Fixed roots include objects referenced from the virtual machine stack, static fields, constant pool, JNI handles, internal VM objects, synchronized objects, and JMX/JVMTI callbacks. Temporary roots arise during partial or generational collections to ensure objects referenced across regions are not mistakenly reclaimed.

4. Four Types of Java References

Strong Reference : ordinary references (e.g., Object o = new Object();) that prevent garbage collection.

Soft Reference : reclaimed only when memory is low; used for caches.

SoftReference<String> softRef = new SoftReference<>(str);

Weak Reference : cleared at the next GC cycle; used in structures like ThreadLocal to avoid memory leaks.

WeakReference<String> weakRef = new WeakReference<>(str);

Phantom Reference : the weakest reference, used mainly for cleanup notifications such as managing off‑heap memory.

5. Generational Collection Theory

Most collectors follow the generational hypothesis: most objects die young (weak generation hypothesis) while objects that survive many collections become harder to collect (strong generation hypothesis). The heap is split into Young and Old generations, with a remembered set tracking cross‑generation references to avoid scanning the entire old generation.

6. Garbage‑Collection Algorithms

The article lists three families of algorithms:

Mark‑Sweep : marks live objects then sweeps away the rest; suffers from fragmentation and longer pause times as heap size grows.

Mark‑Copy : copies live objects to a new space, eliminating fragmentation but requiring twice the memory during collection.

Mark‑Compact : combines marking with compaction, moving live objects to one end of the heap and freeing the rest.

7. Stop‑The‑World (STW)

During certain GC phases, all Java application threads are paused (except GC helper threads), ensuring a consistent view of memory.

8. Why STW Is Needed

Without STW, concurrent mutations could cause the collector to misidentify live objects, especially in the presence of cyclic references or rapid allocation.

9. How the Collector Finds GC Roots

HotSpot records an OopMap for each stack frame at safe points; during GC, the collector reads these maps to locate root references without scanning the entire stack.

10. OopMap Purpose and Benefits

OopMap records which stack slots contain object references at safe points, enabling fast root enumeration and supporting precise (accurate) garbage collection.

11. Safe Points

Safe points are well‑defined locations in the bytecode (method entry, loop back‑edges, exception handlers, etc.) where the VM can safely pause threads for GC. Two interruption strategies are described: pre‑emptive (force‑stop then resume until a safe point) and cooperative (threads poll a flag and pause at the next safe point).

12. Safe Regions

Safe regions extend safe points: a block of code where reference relationships do not change, allowing a thread to remain in a “safe” state while the GC proceeds.

13. Common Garbage Collectors

The article enumerates ten collectors, summarizing their main characteristics:

Serial : single‑threaded, uses copying for the young generation.

ParNew : multithreaded version of Serial for the young generation.

Parallel Scavenge : multithreaded young‑gen collector optimized for throughput.

Serial Old : single‑threaded mark‑compact collector for the old generation.

Parallel Old : multithreaded mark‑compact collector for the old generation.

CMS : concurrent collector that performs most work in parallel with application threads, but can suffer from fragmentation and “floating garbage”.

G1 (Garbage‑First) : region‑based collector that selects regions with the most garbage for reclamation, supporting both young and old generation collection.

14. Three‑Color Marking

During concurrent marking, objects are colored white (unvisited), gray (visited but references not fully processed), or black (fully processed). Incorrect handling of new references (white‑to‑black) or removal of gray references can lead to mis‑marking, which is mitigated by incremental updates and SATB (snapshot‑at‑the‑beginning) techniques.

15. When Stack‑Memory Overflows Occur

Two scenarios cause stack overflow: (1) a thread requests a stack larger than the JVM‑allowed maximum, throwing StackOverflowError; (2) the JVM cannot expand the stack or allocate a new thread stack, throwing OutOfMemoryError.

16. Diagnosing OOM Issues

Enable heap dumps with

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heapdump.hprof

.

Use jstat to monitor memory and GC activity.

Analyze the dump with profiling tools to locate large objects.

17. Class Loading Mechanism

The JVM loads class files into memory, verifies, prepares, resolves, and initializes them. The process follows a fixed order: loading → verification → preparation → (optional) resolution → initialization → unloading.

18. Parent‑Delegation Model

Class‑loader requests are delegated up the hierarchy (bootstrap → extension → application). This ensures class uniqueness (e.g., java.lang.Object is loaded only once) and prevents duplicate definitions.

19. Stack Allocation of Objects

Objects that do not escape the current thread can be allocated on the stack, reducing heap pressure. Escape analysis determines whether an object is eligible for stack allocation.

20. Object Memory Layout

Each object consists of a header (MarkWord and ClassPointer), optional length field for arrays, instance data (field values), and padding to align the object size to an 8‑byte boundary.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMMemory ManagementGarbage Collection
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.