Memory leaks practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Every Java leak in this module has the same shape: something long-lived holds references to objects that are no longer needed. Finding a leak means finding that holder; fixing it means giving the holder a rule for letting go.
Spotting a leak: who holds the reference?
Start from the long-lived holders: static fields, singletons, caches, listener lists, ThreadLocals in pool threads and executors. For each one, ask two questions: does it gain an entry per request, user or event, and what removes entries?
Example 1 · Leak hunt: which of four holders keeps growing?
import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
class ExamPortal { // Holder 1: one entry per course code; the number of courses is fixed. static final Map<String, String> courseNames = new HashMap<>(); // Holder 2: an LRU cache of at most 100 result pages. static final Map<Integer, String> resultCache = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, String> e) { return size() > 100; } }; static final Map<String, Long> loggedIn = new HashMap<>(); // Holder 4: "slow request" records for a report nobody runs. static final List<String> slowRequests = new ArrayList<>();
static void handle(int request) { String course = "CS" + (request % 5); courseNames.put(course, "Course " + course); resultCache.put(request, "page " + request); String user = "u" + request; loggedIn.put(user, (long) request); if (request % 3 == 0) { slowRequests.add("request " + request + " took long"); } loggedIn.remove(user); }}
public class LeakHuntDemo { public static void main(String[] args) { int request = 0; for (int round = 1; round <= 3; round++) { for (int i = 0; i < 3000; i++) { ExamPortal.handle(request++); } System.out.printf("Round %d: courses=%d cache=%d loggedIn=%d slowRequests=%d%n", round, ExamPortal.courseNames.size(), ExamPortal.resultCache.size(), ExamPortal.loggedIn.size(), ExamPortal.slowRequests.size()); } }}Round 1: courses=5 cache=100 loggedIn=0 slowRequests=1000 Round 2: courses=5 cache=100 loggedIn=0 slowRequests=2000 Round 3: courses=5 cache=100 loggedIn=0 slowRequests=3000
What this code does
courseNamesstops at 5 (one per course),resultCachestops at its limit of 100, andloggedInis emptied by the remove inhandle. None of these grow with time.slowRequestsgains 1,000 entries per round and nothing ever removes them: that is the leak. The fix is to keep a counter, or to bound the list to the last few hundred entries.
A holder that grows and has no removal rule is your leak. Not every growing collection is a leak. A map with one entry per course code or per state stops growing when it has seen them all, and an LRU cache stops at its limit. The leak is the one whose size keeps rising with time, like the after-GC heap in a GC log. The fastest check in a test program is to print the size of each holder after a few rounds of work, as Example 1 does. In a running server, a class histogram or two heap dumps answer the same question.
Fixing caches, listeners and ThreadLocal in one service
Each leak type has a standard fix, and a real service often needs all of them at once.
Example 2 · One service, three fixes
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.function.Consumer;
class OrderService { // Cache: bounded LRU (was an unbounded HashMap). final Map<String, String> shopCache = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<String, String> e) { return size() > 50; } }; // Listeners: every add has a matching remove. final List<Consumer<String>> orderListeners = new ArrayList<>(); // Request context: removed in finally. static final ThreadLocal<String> currentCustomer = new ThreadLocal<>();
String info(String shop) { return shopCache.computeIfAbsent(shop, r -> "info of " + r); }
void placeOrder(String customer, String shop) { currentCustomer.set(customer); Consumer<String> tracker = msg -> { }; orderListeners.add(tracker); try { info(shop); for (Consumer<String> l : orderListeners) { l.accept("order placed"); } } finally { orderListeners.remove(tracker); currentCustomer.remove(); } }}
public class FixedServiceDemo { public static void main(String[] args) { OrderService service = new OrderService(); for (int i = 0; i < 10_000; i++) { service.placeOrder("cust-" + i, "shop-" + (i % 400)); } System.out.println("After 10,000 orders:"); System.out.println(" shop cache entries: " + service.shopCache.size()); System.out.println(" order listeners: " + service.orderListeners.size()); System.out.println(" customer on main: " + OrderService.currentCustomer.get()); }}After 10,000 orders: shop cache entries: 50 order listeners: 0 customer on main: null
What this code does
- The shop cache sees 400 shops but holds at most 50, because the LRU limit evicts the least recently used. The per-order listener is removed in
finally, so 10,000 orders leave 0 listeners. currentCustomer.remove()in the samefinallyleaves the thread clean. Here the work runs onmain, soget()there printsnull; in a pool, the next task on that thread would seenulltoo.
- Cache: give it a size limit (LRU with
removeEldestEntry) and, if data goes stale, an expiry time. - Listener: every
addhas a matchingremove, inclose()or afinally, or through a subscription object. - ThreadLocal:
setintry,remove()infinally, because pool threads are reused. - Resources and executors: try-with-resources for anything
AutoCloseable; one executor, shut down at the end.
Predicting WeakReference and WeakHashMap behaviour
Predict by tracing strong paths, not by guessing what the GC "wants".
Example 3 · Predicting five reference cases
import java.lang.ref.SoftReference;import java.lang.ref.WeakReference;import java.util.Map;import java.util.WeakHashMap;
class Token { final String id;
Token(String id) { this.id = id; }
@Override public String toString() { return id; }}
class Holder { final Token token;
Holder(Token token) { this.token = token; }}
public class PredictWeakDemo { public static void main(String[] args) throws InterruptedException { Token kept = new Token("kept"); WeakReference<Token> w1 = new WeakReference<>(kept); WeakReference<Token> w2 = new WeakReference<>(new Token("dropped")); SoftReference<Token> s1 = new SoftReference<>(new Token("soft"));
Map<Object, String> map = new WeakHashMap<>(); map.put("literal", "A"); map.put(new Token("new-key"), "B"); Map<Token, Holder> backRef = new WeakHashMap<>(); Token selfKey = new Token("self-key"); backRef.put(selfKey, new Holder(selfKey)); selfKey = null;
System.gc(); Thread.sleep(100);
System.out.println("1. weak to a live local: " + w1.get()); System.out.println("2. weak to a dropped obj: " + w2.get()); System.out.println("3. soft, plenty of heap: " + s1.get()); System.out.println("4. WeakHashMap keys: " + map.keySet()); System.out.println("5. value holds its key: " + backRef.size() + " entry, still " + kept.id); }}1. weak to a live local: kept 2. weak to a dropped obj: null 3. soft, plenty of heap: soft 4. WeakHashMap keys: [literal] 5. value holds its key: 1 entry, still kept
What this code does
- Case 1 keeps
keptin a local variable used later, so its weak reference survives; case 2 has no strong path, so it is cleared. Case 3 is soft with plenty of heap, so it stays. - In case 4 only the pooled literal survives; the fresh
Tokenkey is removed. In case 5 theHoldervalue points to its own key, so that entry can never be removed.
If any strong path reaches the object, from a live local variable, a static field, a literal in the String pool, an enum constant, a cached small Integer, or the map's own value, then a weak reference to it is not cleared and a WeakHashMap entry with it as key is not removed. If no strong path remains, a weak reference is cleared at a GC that examines the object, and the WeakHashMap drops the entry on its next operation. A soft reference with plenty of free heap usually survives; it is guaranteed to be cleared only before an OutOfMemoryError. GC timing is never exact, so such programs print a sample output: the shape is reliable on HotSpot with default settings, the exact moment is not.
Answering "how would you find a memory leak?"
Interviewers want a method, not a tool list.
jps -l # find the process idjcmd <pid> GC.class_histogram # instances and bytes per classjcmd <pid> GC.heap_dump leak-1.hprof # a dump now...jcmd <pid> GC.heap_dump leak-2.hprof # ...and one an hour later, to compareA good answer has four steps: observe the symptom (after-GC heap climbing in the GC log, then OutOfMemoryError), measure which classes grow (a class histogram, taken twice), find the holder (a heap dump and the path from the growing objects to a GC root), and fix and verify (remove, bound or close, then confirm the after-GC heap stays flat).
The tools come from the JDK: jps lists running JVMs, jcmd <pid> GC.class_histogram counts instances per class, and jcmd <pid> GC.heap_dump writes a heap dump file. The Diagnosing Memory Problems module covers them step by step.
Example 4 · A class histogram of a leaking program
java LeakingSessions # in one terminal: 50,000 guest sessions in a static HashMapjps -l # in another: find its process idjcmd <pid> GC.class_histogram<pid>: num #instances #bytes class name (module) ------------------------------------------------------- 1: 152659 54107600 [B (java.base@21.0.7) 2: 102577 2461848 java.lang.String (java.base@21.0.7) 3: 50895 1628640 java.util.HashMap$Node (java.base@21.0.7) 4: 50000 1200000 UserSession ...
What this code does
- A real run on JDK 21 (trimmed after the first four rows). The test program puts 50,000
UserSessionobjects, each with a 1,000-byte cart, into a static map and then waits sojcmdcan attach.[Bmeansbyte[]. - The numbers line up: 50,000 sessions, about 50,000
HashMap$Nodeentries, two strings per session (map key and user name), and the carts inside the 54 MB of byte arrays. A second histogram an hour later showing bigger counts confirms the leak.
Finish up
Mark complete & continue
Next: Find and inspect a JVM with jps and jcmd