What a memory leak means in Java
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The garbage collector frees only objects your program can no longer reach. A memory leak in Java is the opposite case: objects your program will never use again, but can still reach, so the collector must keep them.
A leak: objects you no longer need but can still reach
A memory leak in Java is when objects that are no longer needed stay reachable, often from a growing collection, so the garbage collector can never free them.
A memory leak in Java is a group of objects that the program will never use again but that is still reachable from a GC root, such as a static field or a local variable of a running method.
Example 1 · A static list that keeps every receipt
import java.util.ArrayList;import java.util.List;
class Receipt { final String studentId; final int amount;
Receipt(String studentId, int amount) { this.studentId = studentId; this.amount = amount; }}
class FeeCounter { // Every receipt ever made, kept "for debugging". Nothing reads it, nothing removes from it. static final List<Receipt> allReceipts = new ArrayList<>(); static long total = 0;
static void collectFee(String studentId, int amount) { Receipt r = new Receipt(studentId, amount); total += r.amount; allReceipts.add(r); // the leak: one line }}
class FixedFeeCounter { static long total = 0;
static void collectFee(String studentId, int amount) { Receipt r = new Receipt(studentId, amount); total += r.amount; // use the receipt, then let it go }}
public class FeeReceiptLeakDemo { public static void main(String[] args) { for (int day = 1; day <= 3; day++) { for (int i = 0; i < 5_000; i++) { FeeCounter.collectFee("S" + i, 1000); FixedFeeCounter.collectFee("S" + i, 1000); } System.out.println("Day " + day + ": leaky counter keeps " + FeeCounter.allReceipts.size() + " receipts, fixed counter keeps 0"); } System.out.println("Both totals: Rs " + FeeCounter.total + " and Rs " + FixedFeeCounter.total); }}Day 1: leaky counter keeps 5000 receipts, fixed counter keeps 0 Day 2: leaky counter keeps 10000 receipts, fixed counter keeps 0 Day 3: leaky counter keeps 15000 receipts, fixed counter keeps 0 Both totals: Rs 15000000 and Rs 15000000
What this code does
- Both counters compute the same total. The leaky one also adds every
Receiptto a static list that nothing ever reads, so after three days 15,000 receipts are still reachable and the GC must keep them. - The fixed counter uses each receipt and drops it at the end of
collectFee. Once the method returns, nothing reaches the receipt, so it is garbage and can be collected.
The garbage collector cannot know you are "done" with an object. It only checks whether a path of references leads to it. So the classic leak is one line: list.add(x) or map.put(k, v) into a collection that lives for the whole run, with no matching remove. Each added object is small, but the collection grows with every request, every payment or every login, and the objects inside it can never be collected. Fixing it means cutting the path: remove the entry when you are done, keep only the number you need instead of the whole object, or put a limit on the collection.
Trace the code
Watch a static list hold on
Variables
- ALL
- []
Output
(nothing printed yet)Line 13main calls print with "R1". The static list ALL is empty.
free. In Java, a leak is a reference you forgot to drop. The collector does its job correctly; the program tells it to keep the objects.Symptoms: heap after GC keeps growing, then OutOfMemoryError
The best sign of a leak is the heap used after GC: how much memory is still in use right after a collection has freed everything it could.
Example 2 · Watching a leak grow: heap used after GC
import java.util.ArrayList;import java.util.List;
class ResultPage { final String rollNo; final byte[] pdf = new byte[2_000_000];
ResultPage(String rollNo) { this.rollNo = rollNo; }}
public class ResultsServerLeak { // "Recently viewed" pages, kept for debugging. Nobody ever removes them. static final List<ResultPage> recentPages = new ArrayList<>();
static void showResult(String rollNo) { ResultPage page = new ResultPage(rollNo); recentPages.add(page); // the leak }
static long usedAfterGcMb() { System.gc(); // only a request, but HotSpot usually honours it Runtime rt = Runtime.getRuntime(); return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024); }
public static void main(String[] args) { for (int minute = 1; minute <= 6; minute++) { for (int i = 0; i < 2; i++) { showResult("R" + minute + "-" + i); } System.out.println("Minute " + minute + ": pages kept = " + recentPages.size() + ", heap used after GC = " + usedAfterGcMb() + " MB"); } }}Minute 1: pages kept = 2, heap used after GC = 5 MB Minute 2: pages kept = 4, heap used after GC = 8 MB Minute 3: pages kept = 6, heap used after GC = 12 MB Minute 4: pages kept = 8, heap used after GC = 16 MB Minute 5: pages kept = 10, heap used after GC = 20 MB Minute 6: pages kept = 12, heap used after GC = 24 MB
What this code does
- Each minute, 2 result pages of about 2 MB are added to
recentPagesand never removed. After everySystem.gc()the used heap is about 4 MB higher: nothing in the list can be freed. - The MB numbers differ on your computer, but the shape is the point: the after-GC number only goes up. With the default heap this short run finishes; a real server running all day does not.
Example 3 · The same leak with a 16 MB heap
javac ResultsServerLeak.javajava -Xmx16m -Xlog:gc ResultsServerLeak[0.016s][info][gc] Using G1 [0.128s][info][gc] GC(0) Pause Full (System.gc()) 5M->4M(16M) 5.287ms Minute 1: pages kept = 2, heap used after GC = 4 MB ... [0.147s][info][gc] GC(3) Pause Full (System.gc()) 8M->8M(16M) 4.284ms Minute 2: pages kept = 4, heap used after GC = 8 MB ... [0.155s][info][gc] GC(6) Pause Full (System.gc()) 12M->12M(16M) 4.172ms Minute 3: pages kept = 6, heap used after GC = 12 MB ... [0.167s][info][gc] GC(11) Pause Full (G1 Compaction Pause) 14M->14M(16M) 4.120ms ... [0.173s][info][gc] GC(13) Pause Full (G1 Compaction Pause) 14M->14M(16M) 4.870ms ... [0.177s][info][gc] GC(16) Pause Full (G1 Compaction Pause) 14M->14M(16M) 3.742ms [0.180s][info][gc] GC(17) Pause Full (G1 Compaction Pause) 14M->14M(16M) 3.375ms Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at ResultPage.<init>(ResultsServerLeak.java:6) at ResultsServerLeak.showResult(ResultsServerLeak.java:18) at ResultsServerLeak.main(ResultsServerLeak.java:32)
What this code does
- A real run on HotSpot (JDK 21, G1), with some Pause Young and Concurrent lines cut and shown as
.... The after-GC number goes 4M, 8M, 12M, then Full GCs run back to back and free nothing:14M->14M. - The program is the one from Example 2, unchanged; only
-Xmx16mmakes the heap small enough to fill in a second. The stack trace namesResultPage.<init>, the last allocation, not theaddline that leaked.
In a GC log it is the number after the arrow, for example 12M in Pause Full (System.gc()) 12M->12M(16M). With a leak, this after-GC number climbs with time and never comes back down. As the heap fills, collections come more often and free less, so the program slows down: more and longer pauses, and Full GCs that free almost nothing. Finally an allocation finds no room, and the JVM throws java.lang.OutOfMemoryError: Java heap space. A slow climb can take hours or days. A results server that is fine at 9 am can start crawling at 10 am, when lakhs of students check their marks at once, and crash before noon.
new ResultPage, while the real bug is recentPages.add. The Diagnosing Memory Problems module shows how heap dumps find the real holder.A leak versus a program that simply needs more memory
High memory use is not always a leak. A program that loads an 8 MB marks table and keeps it for the whole run uses a lot, but its after-GC number stays flat.
Example 4 · Big but stable versus leaking
import java.util.ArrayList;import java.util.List;
class MarksTable { // Marks of 2 lakh students for 10 subjects, loaded once: about 8 MB. final int[] marks = new int[200_000 * 10];}
public class LeakOrJustBigDemo { static final List<byte[]> leakedPages = new ArrayList<>();
static long usedAfterGcMb() { System.gc(); Runtime rt = Runtime.getRuntime(); return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024); }
public static void main(String[] args) { MarksTable table = new MarksTable();
System.out.println("Big but stable:"); for (int minute = 1; minute <= 4; minute++) { for (int i = 0; i < 100; i++) { byte[] page = new byte[50_000]; // built, sent, then dropped page[0] = (byte) table.marks[i]; } System.out.println(" minute " + minute + ": " + usedAfterGcMb() + " MB after GC"); }
System.out.println("Leaking:"); for (int minute = 1; minute <= 4; minute++) { for (int i = 0; i < 100; i++) { leakedPages.add(new byte[50_000]); // kept forever by a static list } System.out.println(" minute " + minute + ": " + usedAfterGcMb() + " MB after GC"); } System.out.println("Table still in use: " + table.marks.length + " entries"); }}Big but stable: minute 1: 8 MB after GC minute 2: 8 MB after GC minute 3: 8 MB after GC minute 4: 8 MB after GC Leaking: minute 1: 13 MB after GC minute 2: 18 MB after GC minute 3: 23 MB after GC minute 4: 28 MB after GC Table still in use: 2000000 entries
What this code does
- The marks table is about 8 MB and stays for the whole run, yet the after-GC number is flat at 8 MB: every page made inside the loop is dropped and collected. That is a plateau, not a leak.
- The second loop keeps every page in a static list, so the after-GC number climbs by about 5 MB per minute. Your numbers will differ; the flat line versus the climbing line will not.
Example 5 · One heap size, two outcomes
java -Xmx16m LeakOrJustBigDemoBig but stable: minute 1: 8 MB after GC minute 2: 8 MB after GC minute 3: 8 MB after GC minute 4: 8 MB after GC Leaking: minute 1: 13 MB after GC Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at LeakOrJustBigDemo.main(LeakOrJustBigDemo.java:33)
What this code does
- A 16 MB heap is enough for the big-but-stable part forever, because it never needs more than about 8 MB after GC. The leaking part fails within its second minute.
- Doubling the heap would let the leaking loop survive a few more minutes and then fail the same way. More heap fixes the first kind of program, never the second.
That is a plateau: a level that memory rises to and then stays at. A leak never reaches a plateau. Its after-GC number goes up with every hour or every batch of requests. Giving it a bigger heap with -Xmx only moves the crash later; a program that simply needs more memory is fixed by a bigger heap.
- Leak: after-GC heap grows with time or with the number of requests, and never levels off.
- Needs more memory: after-GC heap rises to a level and stays there; it fails quickly or not at all.
- Leak: a bigger
-Xmxdelays the OutOfMemoryError. Needs more memory: a bigger-Xmxfixes it. - Normal: the heap before GC goes up and down like a saw. That is garbage being made and freed, not a leak.
Interview answer: can Java leak memory?
Yes. Java cannot leak unreachable objects, because the garbage collector frees them, even in cycles. But it can leak reachable objects that the program no longer needs, and those cause the same OutOfMemoryError as a leak in C.
// A classic leak, in three linesstatic final Map<String, Session> sessions = new HashMap<>();
void onLogin(String user) { sessions.put(user, new Session(user)); }void onLogout(String user) { /* forgot sessions.remove(user) */ }Common causes, each covered in this module: static collections and unbounded caches, listeners that are never removed, ThreadLocal values in thread pools, unclosed resources, and inner classes that hold their outer object. A good answer names one cause, how you would spot it (after-GC heap climbing in the GC log) and how you would fix it (remove, bound or close).
Next step
Check your understanding
12 quick questions