Stop 12 · Multithreading & JVM InternalsTopics · 9/9

Garbage Collection Basics

Part of the Java Roadmap

In short

In Java you never call free(). The garbage collector finds objects nobody can reach anymore and reclaims their memory. Understanding it helps you avoid leaks and long pauses.

The JVM automatically frees objects that are no longer reachable. Most collectors are generational, and G1 is the default in modern JDKs. You can still leak memory by holding unwanted references.

The jaadu pushes a kabadiwala cart through a building courtyard, collecting loose old newspapers and bottles while boxes tied with strings to balconies stay put.

Think of it like this

The kabadiwala round

Every week the kabadiwala visits your building. Anything still tied to a flat with a string, he leaves alone. Anything lying loose with no string to anyone, he takes away. The GC starts from roots like running threads and static fields, follows every reference, and collects whatever it can't reach.

Watch it happen

What is reachable from GC roots

GC roots
main thread
static cache
Cart
Item
old Session

1/4The GC starts from roots: live thread stacks, static fields and JNI references.

The big ideas

What you need to know

Reachability

An object is alive if any chain of references leads to it from a GC root. Cycles of unreachable objects are collected too.

Generations

Most objects die young. New objects go to the young generation, which is collected often and cheaply. Survivors move to the old generation.

G1 by default

G1 is the default collector on modern JDKs. ZGC is an option for very low pause times on large heaps.

Leaks still happen

Static collections that only grow, unclosed listeners and caches without limits keep objects reachable forever.

See it in code

Walk through the code

java
1import java.util.*;2 3public class SessionStore {4    // Leak: this map only ever grows5    private static final Map<String, byte[]> SESSIONS = new HashMap<>();6 7    static void login(String userId) {8        SESSIONS.put(userId + System.nanoTime(), new byte[100_000]);9    }10 11    static void logout(String key) {12        SESSIONS.remove(key);   // fix: always remove when done13    }14 15    public static void main(String[] args) {16        for (int i = 0; i < 1_000_000; i++) {17            login("user" + i);18        }19    }20}

1/3A static field is a GC root. Everything inside this map stays reachable.

Run with java -Xmx128m -Xlog:gc SessionStore.java and watch GC work harder until OutOfMemoryError.

Save yourself the pain

Common mistakes

Oops

Calling System.gc() to fix memory problems.

Do this instead

It is only a hint and may cause a full pause. Find out what is keeping objects reachable instead.

Oops

Thinking Java cannot have memory leaks.

Do this instead

Anything still referenced, like entries in a static map, can never be collected. That is a Java memory leak.

Oops

Relying on finalize() to clean up files or sockets.

Do this instead

finalize is deprecated for removal. Use try-with-resources so close() runs at a known time.

Your mission

Watch the collector

~25 min

Quick check

Two objects reference each other, but nothing else references either of them. What happens?

Go deeper

  1. 1Learn what makes an object eligible for garbage collection.
  2. 2Watch heap usage of a running app with VisualVM or JDK Mission Control.
  3. 3Find a memory leak caused by an ever-growing static collection.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge