Skip to content

Expert · Design patterns, JVM internals and interviews · topic 58 of 60 · 25 min

JVM memory and garbage collection

Explanation

Each thread has a stack for method calls and local variables; all objects live on the shared heap. The garbage collector (G1 by default since Java 9) frees objects that are no longer reachable, so you never free memory yourself. Class metadata lives in Metaspace. Too little heap gives OutOfMemoryError; too-deep recursion gives StackOverflowError. -Xms and -Xmx set the heap size.

Where things live

AreaHoldsPerError when full
StackMethod call frames, local variables, primitive locals and referencesThreadStackOverflowError
HeapAll objects and arrays (new …)JVM (shared)OutOfMemoryError: Java heap space
MetaspaceClass metadata (since Java 8; replaced PermGen)JVMOutOfMemoryError: Metaspace
java
void placeOrder() {
    int qty = 2;                          // on this thread's stack
    Order order = new Order("Asha", qty); // reference on the stack, Order object on the heap
}                                          // frame popped; the Order is unreachable unless stored elsewhere

Garbage collection

The garbage collector (GC) finds objects that cannot be reached from any "root" (local variables of running threads, static fields, and so on) and reclaims their memory. Most objects die young (temporary strings, DTOs for one request), so collectors split the heap into a young generation (collected often and quickly) and an old generation (for long-lived objects, collected less often). This is called generational collection.

  • G1 (Garbage-First): the default collector since Java 9; balances throughput and pause times for most server apps.
  • ZGC and Shenandoah: low-pause collectors for very large heaps and latency-sensitive services.
  • Parallel GC: maximum throughput for batch jobs that can tolerate longer pauses.

Sizing the heap

bash
java -Xms512m -Xmx2g -jar app.jar          # start with 512 MB, allow up to 2 GB of heap
java -XX:+UseZGC -Xmx8g -jar app.jar        # choose a collector
java -Xlog:gc -jar app.jar                  # log GC activity
jcmd <pid> GC.heap_info                     # inspect a running JVM
In containers, recent JVMs read the container memory limit; -XX:MaxRAMPercentage is another common setting.

Memory leaks in Java

The GC frees only UNREACHABLE objects. A leak in Java means something still references objects you no longer need, so they can never be collected. Common causes: static collections that only grow (a static Map used as a cache with no limit), listeners or callbacks registered and never removed, ThreadLocal values not cleaned up in thread pools, and unclosed resources.

java
class SessionCache {
    private static final Map<String, Session> SESSIONS = new HashMap<>();   // grows forever
    static void add(Session s) { SESSIONS.put(s.id(), s); }                 // never removed → leak
}
// Fix: remove on logout, add expiry, or use a bounded cache (Caffeine) / a WeakHashMap where suitable.

Errors to recognise

  • java.lang.OutOfMemoryError: Java heap space → the heap is full of live objects: a leak, or genuinely too little -Xmx.
  • java.lang.StackOverflowError → usually unbounded recursion.
  • GC overhead limit exceeded → the JVM spends almost all its time collecting and freeing almost nothing.
Careful: Calling System.gc() is only a hint and is almost never the fix. The finalize() method is deprecated for removal (Java 18, JEP 421) and should not be used for clean-up; use try-with-resources. To investigate memory problems, take a heap dump (jcmd <pid> GC.heap_dump file.hprof or -XX:+HeapDumpOnOutOfMemoryError) and analyse it with a tool like Eclipse MAT or VisualVM.
Think of it like this: The heap is a shared godown (warehouse) and the garbage collector is the night staff who clear out any box no shop register refers to any more. A leak is a register entry nobody ever crosses out: the box stays forever, and one day the godown is full.
Tip: "Explain the difference between stack and heap" and "What causes OutOfMemoryError?" are among the most common Java interview questions. Answer with the table above and one leak example.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

JVM memory and garbage collection · 1/6

JVM memory

In this lesson you will see how the JVM manages memory.

Prefer a video by a teacher? Find free videos on “jvm memory model stack vs heap garbage collection g1 explained” on YouTube ↗

In real life: A leak found with a heap dump

An insurance company's quote service ran out of memory every few days. A heap dump taken automatically at the OutOfMemoryError showed 3 million QuoteRequest objects held by a static HashMap that was meant to cache recent quotes but never evicted anything. Replacing it with a size-limited cache with expiry fixed the problem.

bash
java -Xmx1g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -jar quote-service.jar

Practice (0/3 done)

Task 1 · Question

Where does the object created by new Order() live?

Task 2 · Question

A recursive method without a base case crashes with…

Task 3 · Practice

Write a small program that keeps adding 1 MB byte arrays to a static List in a loop. Run it with -Xmx64m and observe the OutOfMemoryError. Run again with -XX:+HeapDumpOnOutOfMemoryError, open the dump in VisualVM or Eclipse MAT, and find what holds the memory. Then fix the "leak" by clearing the list every 10 items.

Quick quiz

Question 1

1.Which is the default garbage collector in modern JDKs?

Question 2

2.What replaced PermGen in Java 8?

Question 3

3.Can Java programs have memory leaks?

Question 4

4.What does -Xmx2g set?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which is the default garbage collector in modern JDKs?

Answer: G1

G1 has been the default since Java 9.

What replaced PermGen in Java 8?

Answer: Metaspace

Class metadata moved to Metaspace.

Can Java programs have memory leaks?

Answer: Yes, when unneeded objects are still referenced

The GC only frees unreachable objects.

What does -Xmx2g set?

Answer: The maximum heap size

-Xss sets the thread stack size.

When can the garbage collector free an object?Related

Answer: When no reachable reference points to it

Reachability decides what is kept.

From Memory and garbage collection

How does Rust decide when to free heap memory?Related

Answer: Ownership rules let the compiler insert the free at the right point

Rust frees a value when its owner goes out of scope, decided at compile time.

From Memory 101: the stack and the heap

Who frees heap memory in C?Related

Answer: The program, by calling free

There is no garbage collector.

From Stack and heap

How does Rust free memory?Related

Answer: Through ownership: a value is freed when its owner goes out of scope

Ownership rules make freeing automatic and predictable, and the compiler checks them.

From What Rust is and why learn it

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Design patterns, JVM internals and interviews” before its exam: Java interview questions, Projects and a Java career.
  2. Module 12 exam: Design patterns, JVM internals and interviews · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. 60 topics left in the course before the final exam.

← Previous: Common design patterns