Fundamentals 20 min read

Mastering JVM Garbage Collection: How Java Frees Memory Efficiently

This article explains the JVM garbage collection mechanism, covering which memory areas are collected, how object reachability is determined, the main GC algorithms, generational collection theory, and JVM heap layout, providing essential knowledge for Java performance tuning.

ITFLY8 Architecture Home
ITFLY8 Architecture Home
ITFLY8 Architecture Home
Mastering JVM Garbage Collection: How Java Frees Memory Efficiently

Preface

The previous article introduced the JVM architecture and runtime data areas; this article focuses on the JVM's core feature—garbage collection. Java frees developers from manual memory management thanks to the GC mechanism and allocation strategies, and proper JVM tuning greatly impacts server performance, making it a must‑know skill for senior Java engineers.

Key questions to answer:

Which memory regions require garbage collection?

How to determine if an object is reclaimable?

How are new objects allocated?

How does garbage collection actually work?

The article follows this structure to answer each question.

Memory areas that need GC.

Methods to judge object reclaimability.

Introduction to mainstream GC algorithms.

JVM memory allocation and GC mechanism.

Now the main content begins.

1. Memory Areas Requiring Garbage Collection

Recall the JVM runtime data areas:

JVM runtime data area

The program counter, Java stack, and native method stack are thread‑private; their memory is released when the method or thread ends, so they do not need GC.

The heap and method area are different. Most Java objects are created on the heap, while the method area stores class metadata, constants, static variables, and JIT‑compiled code. These data are determined at runtime and therefore require dynamic memory management.

The GC mainly targets the Java heap because it offers the highest cost‑effectiveness, especially in the young generation where 70‑99% of memory can be reclaimed in a single pass. The method area is rarely collected due to strict reclamation criteria; for example, JDK 11’s ZGC does not support class unloading.

2. Determining Object Reclaimability

2.1 Reference Counting

Reference counting adds a counter to each object; the counter increments on each new reference and decrements when a reference is cleared. An object with a zero count is considered unreachable. This method fails with cyclic references.

public class Student {
    // friend field
    public Student friend = null;

    public static void void test() {
        Student a = new Student();
        Student b = new Student();
        a.friend = b;
        b.friend = a;
        a = null;
        b = null;
        System.gc();
    }
}

The code creates two Student instances that reference each other, then nulls the local variables. Although no external references exist, the objects’ counters are non‑zero because of the cycle, so reference counting cannot reclaim them.

Circular reference

Java does not use reference counting; it employs reachability analysis.

2.2 Reachability Analysis

The algorithm starts from a set of GC Roots and follows reference chains. Any object not reachable from the roots is considered garbage and can be reclaimed. To perform the analysis, the JVM pauses all user threads (Stop‑The‑World).

Reachability analysis

GC Roots in Java include:

1. Objects referenced from the virtual machine stack (local variables, parameters, temporary variables).
2. Objects referenced by static fields in the method area.
3. Objects referenced by constants in the constant pool (e.g., String literals).
4. Objects referenced by native methods (JNI).
5. JVM internal references such as Class objects for primitive types and permanent exception objects.
6. Objects held by synchronization locks (synchronized).
7. Callback objects, native code caches, and other internal JVM structures.

3. Garbage Collection Algorithms

3.1 Mark‑Sweep

The algorithm consists of a marking phase (using reachability analysis) and a sweeping phase that frees all marked objects. It is simple but suffers from two drawbacks:

Unstable performance when many objects need to be reclaimed.

Memory fragmentation, which can trigger additional GCs for large allocations.

Mark‑Sweep algorithm

3.2 Mark‑Copy

Two equal‑sized memory regions are used; one is active while the other stays empty. During a GC, live objects are copied to the empty region, and the former region is cleared. This algorithm excels when object survival rates are low and is used for the young generation.

Mark‑Copy algorithm

3.3 Mark‑Compact

This algorithm first marks live objects, then compacts them toward one end of the heap, eliminating fragmentation. The trade‑off is that object movement requires a full pause of user threads.

Mark‑Compact algorithm

3.4 Generational Collection

Most JVM implementations adopt a generational strategy based on the observation that most objects die young, while long‑living objects survive many GCs. The heap is divided into a young generation and an old generation.

Object age vs. survival in the JVM

Assumptions:

The majority of objects are short‑lived.

Objects that survive many GCs become harder to collect.

Consequently, the young generation typically uses the Mark‑Copy algorithm, while the old generation may use Mark‑Sweep or Mark‑Compact. Collection types include:

Partial GC: Minor (young), Major (old), Mixed (young + part of old).

Full GC: Collects the entire heap and method area.

4. JVM Memory Allocation and GC Mechanism

4.1 Heap Layout

The Java heap is the largest memory region managed by the JVM and is divided into young and old generations. The young generation consists of Eden, From Survivor, and To Survivor (default ratio 8:1:1). Since JDK 8, the permanent generation has been removed.

JVM heap layout

4.2 Principles of Generational Collection

4.2.1 Allocation and Collection in the Young Generation

Objects are first allocated in Eden. When Eden is full, a Minor GC is triggered. The typical Eden : From : To ratio is 8 : 1 : 1, leaving about 10% of the young generation unused as a safety margin. During a Minor GC, live objects are copied to the To Survivor space, and their age is incremented.

First Minor GC illustration

Subsequent Minor GCs alternate the roles of the Survivor spaces (S0 and S1), copying live objects from Eden and the current From Survivor to the new To Survivor and increasing their age.

Subsequent Minor GC illustration

4.2.2 Promotion to the Old Generation

Objects are promoted to the old generation under the following conditions:

Long‑lived objects: when an object's age reaches a threshold (default 15), it is moved to the old generation. The threshold can be changed with -XX:MaxTenuringThreshold.

Promotion illustration (original image not available)

Large objects: big objects (e.g., large strings or arrays) can be allocated directly in the old generation using -XX:PretenureSizeThreshold to avoid costly copying.

Dynamic age judgment: if the total size of objects of a certain age exceeds half of the Survivor space, those objects are promoted early, regardless of the MaxTenuringThreshold.

Handle Promotion (space allocation guarantee): before a Minor GC, the JVM checks whether the old generation has enough contiguous space to accommodate all objects that might be promoted. If not, it may fall back to a Full GC depending on -XX:HandlePromotionFailure settings.

Summary

This article introduced the JVM garbage collection mechanism with extensive diagrams and examples. Future articles will cover specific collectors such as ZGC and Shenandoah, the latest advancements in JVM GC technology.

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.

JVMGC Algorithmsjvm-tuninggarbage-collectionmemory-management
ITFLY8 Architecture Home
Written by

ITFLY8 Architecture Home

ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.

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.