Memory leak diagnosis
What you will learn
A managed-memory leak is often an ownership bug: the application keeps references long after their useful lifetime. Diagnose growth under comparable workloads and remove unintended retention paths rather than blindly increasing the heap.
- Reproduce bounded unintended retention.
- Implement a capacity or lifecycle policy.
- Explain how to verify a fix without relying on GC timing.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Use only trusted local classes and fixed synthetic data. Never run these diagnostics against another person’s process. The runner enforces a process deadline.
Model retained objects without stress
public class Main { static final java.util.List<byte[]> history = new java.util.ArrayList<>(); public static void main(String[] args) throws Exception { for (int i = 0; i < 3; i++) history.add(new byte[8]); System.out.println(history.size()); history.clear(); System.out.println(history.size()); }}Expected output:
30The static list held three arrays; clear removes its element references. No claim is made about when GC reclaims their storage.
Common retaining paths
A static collection, unbounded cache, listener registry or long-lived thread-local value can retain objects. A small wrapper may retain a large graph. For a listener, the registry may retain its callback, which captures a session. For thread locals in pooled threads, remove values in finally. For native resources, close resources explicitly. A high allocation rate alone is not evidence of a leak.
Test a logical invariant
A cache intended to hold two entries should never hold three after a successful insertion. Use an access-ordered LinkedHashMap for a single-threaded LRU example; the access-order constructor changes ordering on reads. Remove the eldest after insertion when over capacity. This demonstration is count-bounded, not byte-bounded, and does not address concurrency. Real cache policies may require time expiration, weight limits and a maintained library.
Measure before and after
Repeat a finite synthetic workload, record the expected business count, and compare live-set trends over equivalent phases. Investigate retained paths with a heap analyzer only when necessary and authorized. Verify that the fix preserves required functionality and that retention plateaus under the intended load. A stable logical entry count is useful evidence but does not prove process memory cannot leak. Native leaks need separate observations. Avoid forcing OOM or treating a larger heap as a permanent fix.
Bound an LRU cache
public class Main { static class Cache extends java.util.LinkedHashMap<String,Integer> { private static final long serialVersionUID = 1L; Cache() { super(4, 0.75f, true); } @Override protected boolean removeEldestEntry(java.util.Map.Entry<String,Integer> eldest) { return size() > 2; } } public static void main(String[] args) throws Exception { var cache = new Cache(); cache.put("A", 1); cache.put("B", 2); cache.get("A"); cache.put("C", 3); System.out.println(cache.keySet()); System.out.println(cache.size()); }}Expected output:
[A, C]2A was recently read, so B is eldest. This is a local single-threaded count-bounded cache.
Clean thread-local state
public class Main {
public static void main(String[] args) throws Exception { var context = new ThreadLocal<String>(); try { context.set("synthetic-request"); System.out.println(context.get()); } finally { context.remove(); } System.out.println(context.get() == null); }}Expected output:
synthetic-requesttrueCleanup happens even on an exception. Default ThreadLocal initial value is null; this tests logical state, not memory reclamation.
Common mistakes
Do not rely on System.gc or a weak reference to replace ownership rules. Do not treat an unbounded static map as a cache, assume a count limit implies a byte limit, or diagnose a leak from one RSS reading.
Practice
Build a single-threaded insertion-order history with a capacity of two using ArrayDeque. Insert A, B and C; remove the oldest if over capacity. Print [B, C] and 2.
Expected output:
[B, C]2Compare your answer with the manual practice criteria.
Official reading: Diagnostics · References · Collectors. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory leak diagnosis — knowledge check
Original memory and diagnostics questions.
What is a common Java memory leak?
What can a static collection do?
What does a two-entry cache limit guarantee?
How should pooled-thread context be cleaned?
Which comparison is most useful for leak diagnosis?