Garbage Collection and Memory Leaks
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)"Java has garbage collection, so can it leak memory?" is a favourite trap question. The interviewer is checking that you know how GC decides what is garbage, that you cannot force it, and how an unwanted but reachable object fills the heap.
Reachability, GC roots and the generational heap
GC root is a reference the JVM always treats as alive, such as a local variable on a thread's stack, a static field or a running thread. An object is garbage when no chain of references from a root reaches it.
An object becomes eligible for GC in four ways. This program shows each one, including two objects that point at each other but are unreachable.
Example 1 · Four ways an object becomes eligible for GC
public class EligibilityDemo { static class Ticket { final String pnr; Ticket partner;
Ticket(String pnr) { this.pnr = pnr; } }
static void bookAndForget() { Ticket local = new Ticket("PNR-3"); System.out.println("3. method-local object created: " + local.pnr); }
public static void main(String[] args) { Ticket t1 = new Ticket("PNR-1"); t1 = null; // 1. reference set to null System.out.println("1. PNR-1 now has no reference: eligible");
Ticket t2 = new Ticket("PNR-2a"); t2 = new Ticket("PNR-2b"); // 2. reference reassigned System.out.println("2. PNR-2a lost its only reference, t2 is " + t2.pnr);
bookAndForget(); System.out.println(" after return, PNR-3 is unreachable: eligible");
Ticket a = new Ticket("PNR-4"); Ticket b = new Ticket("PNR-5"); a.partner = b; b.partner = a; a = null; b = null; // 4. island of isolation System.out.println("4. PNR-4 and PNR-5 refer to each other but no root reaches them: eligible"); }}1. PNR-1 now has no reference: eligible 2. PNR-2a lost its only reference, t2 is PNR-2b 3. method-local object created: PNR-3 after return, PNR-3 is unreachable: eligible 4. PNR-4 and PNR-5 refer to each other but no root reaches them: eligible
What this code does
- PNR-1 loses its reference to
null, PNR-2a to reassignment, and PNR-3 whenbookAndForgetreturns and its stack frame disappears. - PNR-4 and PNR-5 still point at each other, but no GC root reaches them, so tracing GC collects both. Reference counting would never free such a cycle.
GC traces from the roots, so an island of isolation like PNR-4 and PNR-5 is collected; Java does not use reference counting. Eligible does not mean collected now: the JVM decides when to run GC.
Most objects die young, so the heap is generational: new objects go to the young generation (Eden plus two survivor spaces), collected often and cheaply in a minor GC; survivors are promoted to the old generation, collected less often. A stop-the-world pause stops all application threads while part of a collection runs.
Order of execution
Order an object's journey
Put the life of a long-lived object in the young generation in order.
Can you force GC? System.gc() and finalize
Stop-the-world is a pause in which the JVM stops all application threads while the garbage collector does part of its work. Longer pauses mean slower responses.
You can only request a collection. This program asks for GC with System.gc() and shows that an object held by a weak reference is kept while a strong reference exists.
Example 2 · System.gc() is only a request
import java.lang.ref.WeakReference;
public class GcRequestDemo { public static void main(String[] args) throws InterruptedException { Object report = new Object(); WeakReference<Object> weak = new WeakReference<>(report);
System.gc(); System.out.println("strongly reachable, still there after gc(): " + (weak.get() != null));
report = null; // drop the only strong reference for (int i = 0; i < 20 && weak.get() != null; i++) { System.gc(); // only a request Thread.sleep(20); } System.out.println("unreachable, collected after gc() request: " + (weak.get() == null)); }}strongly reachable, still there after gc(): true unreachable, collected after gc() request: true
What this code does
- While
reportholds a strong reference, the object survives any GC. Afterreport = null, the only reference left is weak, so a collection clears it. - The loop calls
System.gc()a few times because the JVM is free to ignore or delay the request; that is why you cannot rely on it in real code.
System.gc() only requests a collection; the JVM may ignore it (for example with -XX:+DisableExplicitGC), and calling it in application code often triggers an expensive full collection. Model answer: "You cannot force GC; you can only make objects unreachable and request it."
finalize() was meant to run before collection, but there was no guarantee when or whether it ran, and it slowed GC. It has been deprecated since Java 9 and deprecated for removal since Java 18. Release resources with close() and try-with-resources, and use Cleaner only as a safety net.
Collectors in one line: Serial, Parallel, G1, ZGC
G1 is the default garbage collector since Java 9. It splits the heap into regions, collects the most garbage-filled ones first, and aims for a pause-time goal set with -XX:MaxGCPauseMillis.
Each collector trades pause time against throughput. This program prints the Java version, the collectors the JVM is running, and the maximum heap.
Example 3 · Which collector is running?
import java.lang.management.GarbageCollectorMXBean;import java.lang.management.ManagementFactory;
public class CollectorInfoDemo { public static void main(String[] args) { System.out.println("Java version: " + Runtime.version().feature()); for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { System.out.println("collector: " + gc.getName()); } System.out.println("max heap (MB): " + Runtime.getRuntime().maxMemory() / (1024 * 1024)); }}Java version: 21 collector: G1 Young Generation collector: G1 Concurrent GC collector: G1 Old Generation max heap (MB): 1882
What this code does
- On a typical machine with Java 9 or later the default is G1, which reports its young and old collections (and, from Java 20, a concurrent one). Your heap size depends on your RAM.
- Run with
-XX:+UseSerialGC,-XX:+UseParallelGCor-XX:+UseZGCto see the names change.
One line each for the interview:
- Serial (
-XX:+UseSerialGC): one GC thread, stop-the-world; small heaps and tiny containers. - Parallel (
-XX:+UseParallelGC): many GC threads, best throughput for batch jobs. - G1 (
-XX:+UseG1GC): regions and a pause goal; the default. - ZGC (
-XX:+UseZGC) and Shenandoah: mostly concurrent, pauses of about a millisecond even on huge heaps.
CMS was removed in Java 14, so mention it only as history. Run with -Xlog:gc to see what GC is doing.
Memory leaks in Java
Memory leak in Java is when objects that are no longer needed are still reachable, so the garbage collector can never free them. The heap grows until OutOfMemoryError.
A static list that only grows is the classic leak. This program adds 1000 entries to one and to a bounded cache, then compares their sizes.
Example 4 · A growing static list vs a bounded cache
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class LeakFixDemo { // Leak: a static list that only grows static final List<String> auditLog = new ArrayList<>();
// Fix: a bounded cache that drops the oldest entry static final Map<Integer, String> recentResults = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest) { return size() > 3; } };
public static void main(String[] args) { for (int roll = 1; roll <= 1000; roll++) { auditLog.add("viewed result of roll " + roll); // kept forever by a static root recentResults.put(roll, "result-" + roll); } System.out.println("static list size: " + auditLog.size() + " (keeps growing)"); System.out.println("bounded cache size: " + recentResults.size()); System.out.println("cache keeps: " + recentResults.keySet()); }}static list size: 1000 (keeps growing) bounded cache size: 3 cache keeps: [998, 999, 1000]
What this code does
auditLogis reachable from a static field, a GC root, so all 1000 entries stay forever and grow with every request: a classic leak.- The
LinkedHashMapwithremoveEldestEntrynever holds more than 3 entries, so old results become unreachable and GC can free them.
Common causes: static collections that only grow (caches with no limit), unclosed resources, listeners that are never removed, inner classes holding the outer object, and ThreadLocal values on pool threads that are never remove()d.
Diagnose with a heap dump (jcmd <pid> GC.heap_dump file.hprof, or -XX:+HeapDumpOnOutOfMemoryError) analysed in Eclipse MAT or VisualVM: look for the biggest retained objects and the reference chain from a GC root.
Find the bug
Find the leak
Click the line that causes the memory leak.
A request handler runs for days. Which line leaks?
Round 1 of 3Strong, soft, weak and phantom references
Soft reference is cleared only when memory is low, so it suits caches. Weak reference is cleared at the next garbage collection once no strong reference remains.
A strong reference keeps an object alive; weaker kinds let GC reclaim it. This program shows a weak reference and a WeakHashMap entry being cleared while a soft reference stays.
Example 5 · Soft vs weak references and WeakHashMap
import java.lang.ref.SoftReference;import java.lang.ref.WeakReference;import java.util.Map;import java.util.WeakHashMap;
public class ReferenceTypesDemo { public static void main(String[] args) throws InterruptedException { byte[] thumbnail = new byte[1024]; byte[] preview = new byte[1024]; SoftReference<byte[]> soft = new SoftReference<>(thumbnail); WeakReference<byte[]> weak = new WeakReference<>(preview); thumbnail = null; // now only softly reachable preview = null; // now only weakly reachable
Map<Object, String> sessions = new WeakHashMap<>(); Object user = new Object(); sessions.put(user, "logged in"); user = null; // the key is now only weakly reachable
for (int i = 0; i < 20 && (weak.get() != null || !sessions.isEmpty()); i++) { System.gc(); Thread.sleep(20); } System.out.println("weak reference cleared: " + (weak.get() == null)); System.out.println("WeakHashMap entry removed: " + sessions.isEmpty()); System.out.println("soft reference kept (memory is plenty): " + (soft.get() != null)); }}weak reference cleared: true WeakHashMap entry removed: true soft reference kept (memory is plenty): true
What this code does
- The weakly reachable
previewarray and theWeakHashMapentry whose key lost its last strong reference are cleared by GC. - The softly reachable
thumbnailsurvives, because soft references are cleared only when the heap is running low. That is what makes them suitable for caches.
WeakHashMap uses weak keys, so an entry disappears when its key is no longer used elsewhere. A PhantomReference never returns its object (get() is always null); with a ReferenceQueue it reports that an object has been collected, which is how Cleaner runs clean-up actions.
Order of strength: strong, then soft, then weak, then phantom.
Predict the output
Predict the references
Read the code, then pick what it prints.
Round 1 of 2
A phantom reference and a soft reference to one object.
Next step
Check your understanding
12 quick questions