Java memory leaks: detection, heap dumps and analysis

Java's garbage collector frees objects that are unreachable, so a Java memory leak is an object that is still reachable but will never be used again, typically held by a collection that only grows. This page explains reachability and retained size, reproduces leaks of five kinds, and finds them with the same tools you would use in production: heap-after-GC trends, jcmd histograms, heap dumps and JFR's leak profiler.

Share

Contents

What a memory leak is in Java

In C, a leak is memory that was allocated and never freed. Java has no free: the garbage collector reclaims every object that can no longer be reached from a GC root, such as a static field, a local variable of a running thread, or a JNI reference. So in Java a leak is an object that is still reachable but that the program will never use again. The collector cannot know that, so it must keep the object, and everything that object references, forever.

Two sizes matter when looking for the cause. An object's shallow size is its own memory: an ArrayList is a few dozen bytes. Its retained size is everything that would become garbage if that one object disappeared: the same list holding a million byte arrays retains gigabytes. Leaks are found by looking for small objects with huge retained sizes, and then for the chain of references, the path to GC roots, that keeps them alive.

The usual life of a leak: heap use after each collection creeps up, collections become more frequent and longer as the collector works harder for less free space, and finally the JVM throws OutOfMemoryError. The sections below follow that path with the standard JDK tools.

Tools for finding leaks
ToolSinceShowsBest for
GC logs, MemoryMXBeanJDK 9 (-Xlog), JDK 5 (MXBeans)Heap used after each collectionNoticing that a leak exists
jcmd <pid> GC.class_histogramJDK 7Live instances and bytes per classA quick look at what is growing
-XX:+HeapDumpOnOutOfMemoryError, jcmd GC.heap_dumpJDK 6 and earlier, JDK 7Every object and referenceFinding the retaining field
Eclipse MAT, VisualVMSeparate toolsDominator tree, paths to rootsAnalysing heap dumps
JFR event jdk.OldObjectSampleJDK 11 in OpenJDKSampled live objects with allocation site and root pathProduction, where a full dump is too big
Native Memory TrackingJDK 8Memory outside the heapMetaspace, threads, direct buffers

The programs were run on JDK 25. Several of them call System.gc() to make the retained memory visible, which is fine in a demonstration but not in production code.

Symptom: the heap after GC keeps growing

Heap usage always rises and falls as objects are created and collected, so the useful signal is the heap used right after a collection: the memory that is still reachable. In a healthy service it levels off; in a leaking one it climbs.

The program keeps a session for every request in a static map, keyed by a new UUID each time, and never removes them. Each session holds 10 KB. After every 1,000 requests it forces a GC and prints the remaining heap. It then runs jcmd <pid> GC.class_histogram against itself, the first diagnosis step you would run against a live server.

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

// A typical leak: a static cache keyed by something unique, filled but never emptied
public class LeakingCache {

    record Session(String id, byte[] data) {
    }

    static final Map<String, Session> SESSIONS = new HashMap<>();

    static void handleRequest() {
        String id = UUID.randomUUID().toString();            // every request gets a new key
        SESSIONS.put(id, new Session(id, new byte[10240])); // ... and nothing removes it
    }

    static long usedAfterGcMb(MemoryMXBean mem) {
        System.gc();
        return mem.getHeapMemoryUsage().getUsed() / (1024 * 1024);
    }

    public static void main(String[] args) throws Exception {
        MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
        for (int round = 1; round <= 5; round++) {
            for (int i = 0; i < 1000; i++) {
                handleRequest();
            }
            System.out.printf("after %,d requests: heap used after GC %3d MB%n", round * 1000,
                    usedAfterGcMb(mem));
        }

        // Diagnose: the class histogram counts live objects per class (jcmd = JDK tool)
        String jcmd = Path.of(System.getProperty("java.home"), "bin", "jcmd").toString();
        Process p = new ProcessBuilder(jcmd, Long.toString(ProcessHandle.current().pid()),
                "GC.class_histogram").redirectErrorStream(true).start();
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            // keep the column header, the top 3 rows and the rows naming our classes
            r.lines().filter(l -> l.contains("#instances") || l.matches("\\s+[123]:.*")
                    || l.contains("Session") || l.contains(" java.util.HashMap$Node "))
                    .map(l -> l.replaceAll(" \\(java\\.base@[^)]*\\)", ""))
                    .forEach(System.out::println);
        }
        p.waitFor();
    }
}

Output:

Output
after 1,000 requests: heap used after GC  11 MB
after 2,000 requests: heap used after GC  22 MB
after 3,000 requests: heap used after GC  32 MB
after 4,000 requests: heap used after GC  42 MB
after 5,000 requests: heap used after GC  52 MB
 num     #instances         #bytes  class name (module)
   1:         22904       52170624  [B
   2:          5249        1342296  [Ljdk.internal.vm.FillerElement;
   3:         17320         415680  java.lang.String
   5:          7909         253088  java.util.HashMap$Node
   7:          5000         120000  LeakingCache$Session
  • The retained heap grew by about 10 MB per 1,000 requests, exactly what 1,000 never-released 10 KB sessions should cost.
  • The histogram lists live object counts and sizes per class. Byte arrays ([B) dominate with about 52 MB, which says what is filling the heap but not why, since everything uses byte arrays.
  • The useful clue is further down: exactly 5,000 LeakingCache$Session objects after 5,000 requests, held in HashMap$Node entries (the node count is higher because other maps in the JVM use them too). A count of application objects that equals the number of requests ever served points straight at a collection that keeps everything. Taking two histograms some minutes apart and comparing the counts makes this even clearer.

The FillerElement arrays are filler objects the JVM uses to mark unused heap space; they are not part of the leak.

When it runs out: OutOfMemoryError and a heap dump

A histogram shows which classes, but not which references keep them alive. For that you need a heap dump, and the best moment to get one is automatically, when the error happens. The program starts a leaking child JVM with a 64 MB heap and the two flags every production JVM should have.

Java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

// Runs a leaking child JVM with a small heap and the usual production diagnostics flags
public class OutOfMemory {

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("dumps");
        String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
        Process p = new ProcessBuilder(java, "-Xmx64m",
                "-XX:+HeapDumpOnOutOfMemoryError", "-XX:HeapDumpPath=" + dir,
                "-cp", System.getProperty("java.class.path"), "OutOfMemory$Leak")
                .redirectErrorStream(true).start();
        String output = new String(p.getInputStream().readAllBytes());
        int exit = p.waitFor();

        output.lines().filter(l -> l.startsWith("Dumping") || l.contains("OutOfMemoryError")
                || l.startsWith("Heap dump file") || l.startsWith("leak"))
                .map(l -> l.replace(dir.toString(), "DIR").replaceAll("java_pid\\d+",
                        "java_pid...").replaceAll("in [\\d.]+ secs", "in ... secs"))
                .forEach(System.out::println);
        try (var files = Files.list(dir)) {
            for (Path f : files.toList()) {
                System.out.println("dump file " + f.getFileName().toString()
                        .replaceAll("\\d+", "...") + ": " + Files.size(f) / (1024 * 1024)
                        + " MB, exit code " + exit);
                Files.delete(f);
            }
        }
        Files.delete(dir);
    }

    static class Leak {
        public static void main(String[] args) {
            List<long[]> retained = new ArrayList<>();
            while (true) {
                retained.add(new long[1024]);
                if (retained.size() % 2000 == 0) {
                    System.out.println("leak: " + retained.size() + " arrays retained");
                }
            }
        }
    }
}

Output:

Output
leak: 2000 arrays retained
leak: 4000 arrays retained
leak: 6000 arrays retained
java.lang.OutOfMemoryError: Java heap space
Dumping heap to DIR/java_pid....hprof ...
Heap dump file created [68802547 bytes in ... secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
dump file java_pid....hprof: 65 MB, exit code 1

When the heap was exhausted, the JVM wrote a 65 MB .hprof file before the error reached the program. Open such a dump in Eclipse Memory Analyzer (MAT) or VisualVM:

  1. Leak Suspects report (MAT): names the objects that retain most of the heap. Here it would point at the ArrayList holding 6,000+ arrays.
  2. Dominator tree: sorts objects by retained size, the memory that would be freed if that object were gone. A single map or list retaining most of the heap is the typical picture of a leak.
  3. Path to GC roots: shows the chain of references from a static field or a thread to the leaked objects, which tells you which field to fix.

A dump can also be taken from a running process with jcmd <pid> GC.heap_dump /path/file.hprof. Heap dumps contain all data in memory, including passwords and personal data, so store them as securely as a database backup.

Finding the path to the root with JFR

A heap dump of a large production heap can take minutes and many gigabytes. Java Flight Recorder has a cheaper leak profiler: the jdk.OldObjectSample event samples allocations, keeps track of the ones that stay alive, and at the end of the recording can record the reference chain from each one back to a GC root. The program leaks 200,000 small arrays into a static list while also allocating the same number of temporary arrays, records with the profiler, and prints what JFR found.

Java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordedObject;
import jdk.jfr.consumer.RecordingFile;

// JFR's leak profiler: samples allocations that are still alive when the recording ends
public class LeakProfiler {

    static final List<long[]> ORDERS = new ArrayList<>();   // the leak

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("leak", ".jfr");
        try (Recording r = new Recording()) {
            // cutoff=infinity: also record the chain of references back to a GC root
            r.enable("jdk.OldObjectSample").with("cutoff", "infinity");
            r.start();
            for (int i = 0; i < 200000; i++) {
                ORDERS.add(new long[16]);                    // retained: line 22
                long[] temp = new long[16];                  // garbage
                temp[0] = i;
            }
            r.stop();
            r.dump(file);
        }
        List<RecordedEvent> samples = RecordingFile.readAllEvents(file).stream()
                .filter(e -> e.getEventType().getName().equals("jdk.OldObjectSample")
                        && !e.getStackTrace().getFrames().isEmpty())
                .filter(e -> e.getStackTrace().getFrames().get(0).getMethod().getType()
                        .getName().equals("LeakProfiler"))
                .toList();
        System.out.println("live samples from this program: more than 10? "
                + (samples.size() > 10));
        boolean allFromLine22 = samples.stream().allMatch(e -> e.getStackTrace().getFrames()
                .get(0).getLineNumber() == 22);
        System.out.println("all allocated at LeakProfiler.main line 22: " + allFromLine22);

        // Walk the reference chain of one sample: object <- referrer <- ... <- root
        RecordedObject object = samples.get(0).getValue("object");
        while (object != null) {
            RecordedObject type = object.getValue("type");
            RecordedObject ref = object.getValue("referrer");
            String via = "";
            if (ref != null && ref.getValue("field") instanceof RecordedObject f) {
                via = " held by field " + f.getString("name") + " of";
            } else if (ref != null && ref.getValue("array") != null) {
                via = " held by an element of";
            }
            System.out.println("  " + type.getString("name").replace('/', '.') + via);
            object = ref == null ? null : ref.getValue("object");
        }
        RecordedObject root = samples.get(0).getValue("root");
        System.out.println("  root: " + root.getString("system") + ", " + root.getString("type"));
        Files.delete(file);
    }
}

Output:

Output
live samples from this program: more than 10? true
all allocated at LeakProfiler.main line 22: true
  [J held by an element of
  [Ljava.lang.Object; held by field elementData of
  java.util.ArrayList held by field ORDERS of
  java.lang.Class
  root: Threads, Stack Variable
  • Every surviving sample was allocated at line 22, the ORDERS.add line. The temporary arrays from line 23 were allocated just as often but died, so none of them appear: the profiler reports only objects that stayed alive, which is exactly what a leak hunt needs.
  • The reference chain reads bottom to top as the path to the leak: a long[] is an element of an Object[], which is the elementData field of an ArrayList, which is the static field ORDERS of a class. That names the field to fix without opening a heap dump. The root itself is the main thread's stack, which reaches the class through the running main method.
  • In production, start a recording with jcmd <pid> JFR.start settings=profile, dump it with jcmd <pid> JFR.dump filename=app.jfr path-to-gc-roots=true, and open it in JDK Mission Control, whose memory leak view shows the same chains. See Java Flight Recorder.

The fix: bound the collection

The fix is to give the cache a limit. A LinkedHashMap in access order with removeEldestEntry is the simplest LRU cache in the JDK: when it grows past 1,000 entries, it drops the least recently used one. The same 5,000 requests produce:

Java
import java.lang.management.ManagementFactory;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

// The same cache with an upper bound: the least recently used entry is evicted
public class FixedCache {

    record Session(String id, byte[] data) {
    }

    static final int MAX_ENTRIES = 1000;

    @SuppressWarnings("serial")
    static final Map<String, Session> SESSIONS = new LinkedHashMap<>(16, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(Map.Entry<String, Session> eldest) {
            return size() > MAX_ENTRIES;
        }
    };

    public static void main(String[] args) {
        var mem = ManagementFactory.getMemoryMXBean();
        for (int round = 1; round <= 5; round++) {
            for (int i = 0; i < 1000; i++) {
                String id = UUID.randomUUID().toString();
                SESSIONS.put(id, new Session(id, new byte[10240]));
            }
            System.gc();
            System.out.printf("after %,d requests: %,d entries, heap used after GC %3d MB%n",
                    round * 1000, SESSIONS.size(),
                    mem.getHeapMemoryUsage().getUsed() / (1024 * 1024));
        }
    }
}

Output:

Output
after 1,000 requests: 1,000 entries, heap used after GC  11 MB
after 2,000 requests: 1,000 entries, heap used after GC  11 MB
after 3,000 requests: 1,000 entries, heap used after GC  11 MB
after 4,000 requests: 1,000 entries, heap used after GC  11 MB
after 5,000 requests: 1,000 entries, heap used after GC  11 MB

The map stays at 1,000 entries and the heap after GC stays flat at about 11 MB. In real applications, a cache library such as Caffeine adds size limits, expiry by time and statistics.

Other leaks, reproduced

A static map is the textbook case, but three other patterns are just as common in real code. The program reproduces each with counts rather than megabytes, so the result is exact: screens that register listeners and never unregister, map keys changed after insertion, and ThreadLocal values on pooled threads.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class OtherLeaks {

    // 1. Listeners: every screen registers with a long-lived event bus and never leaves
    static final class EventBus {
        final List<Consumer<String>> listeners = new ArrayList<>();

        Runnable register(Consumer<String> l) {
            listeners.add(l);
            return () -> listeners.remove(l);            // the handle to unregister
        }
    }

    static final class Screen {
        final byte[] pixels = new byte[100000];        // what the listener keeps alive

        void onEvent(String e) {
            pixels[0] = (byte) e.length();
        }
    }

    // 2. A key whose hashCode changes after it is stored
    static final class Key {
        int id;

        Key(int id) {
            this.id = id;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Key k && k.id == id;
        }

        @Override
        public int hashCode() {
            return id;
        }
    }

    public static void main(String[] args) throws Exception {
        EventBus bus = new EventBus();
        for (int i = 0; i < 500; i++) {
            Screen s = new Screen();
            bus.register(s::onEvent);                    // screen closed, listener stays
        }
        System.out.println("listeners kept after 500 screens were closed: "
                + bus.listeners.size() + " (" + bus.listeners.size() * 100 / 1000 + " MB)");
        EventBus fixed = new EventBus();
        for (int i = 0; i < 500; i++) {
            Screen s = new Screen();
            Runnable unregister = fixed.register(s::onEvent);
            unregister.run();                            // done in the screen's close()
        }
        System.out.println("with unregister on close: " + fixed.listeners.size());

        Map<Key, String> map = new HashMap<>();
        for (int i = 0; i < 1000; i++) {
            Key k = new Key(i);
            map.put(k, "value " + i);
            k.id += 1000000;                           // changed after insertion
            map.remove(k);                               // looks in the wrong bucket
        }
        System.out.println("map entries after 1,000 put/remove pairs: " + map.size());

        // 3. ThreadLocal on pooled threads: each worker keeps its last value forever
        ThreadLocal<byte[]> buffer = new ThreadLocal<>();
        AtomicInteger inherited = new AtomicInteger();
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            for (int i = 0; i < 100; i++) {
                pool.submit(() -> {
                    if (buffer.get() != null) {
                        inherited.incrementAndGet();         // left over from an earlier task
                    }
                    buffer.set(new byte[1000000]);     // no remove(): stays with the thread
                });
            }
        }
        System.out.println("tasks that found a 1 MB value left by an earlier task: "
                + inherited.get() + " of 100");
    }
}

Output:

Output
listeners kept after 500 screens were closed: 500 (50 MB)
with unregister on close: 0
map entries after 1,000 put/remove pairs: 1000
tasks that found a 1 MB value left by an earlier task: 96 of 100
  • All 500 closed screens were still referenced by the event bus through their method-reference listeners, keeping 50 MB of pixel buffers alive. Returning an "unregister" handle from register and calling it in the screen's close() left 0. Weak references are another option, but they make listener lifetimes depend on the collector, which is harder to reason about.
  • Each key's id was changed after put, so remove looked in the bucket for the new hash code and found nothing: all 1,000 entries stayed, and no lookup can ever reach them again. Keys must be immutable, which records make easy.
  • 96 of the 100 tasks found a 1 MB buffer left by an earlier task on the same pool thread. The values are released only when the 4 threads end, which in a server may be never. Call remove() in a finally block, or use scoped values.

Class loader leaks and Metaspace

Application servers, plugin systems and hot-reload tools load code with a fresh class loader on every deployment. A class can be unloaded only when its class loader, every class it loaded and every instance of those classes are unreachable, so a single surviving instance pins the whole set in Metaspace. The program compiles a tiny Plugin class, "deploys" it 2,000 times with new loaders while a static registry keeps one instance of each, and then clears the registry.

Java
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.tools.ToolProvider;

// Simulates redeploying a plugin 2,000 times while something keeps the old loaders alive
public class ClassLoaderLeak {

    static final List<Object> REGISTRY = new ArrayList<>();   // e.g. a static cache of instances

    static long metaspaceKb() {
        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
            if (pool.getName().equals("Metaspace")) {
                return pool.getUsage().getUsed() / 1024;
            }
        }
        return -1;
    }

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("plugin");
        Files.writeString(dir.resolve("Plugin.java"),
                "public class Plugin { public String toString() { return \"plugin\"; } }");
        ToolProvider.getSystemJavaCompiler().run(null, null, null, "-d", dir.toString(),
                dir.resolve("Plugin.java").toString());
        URL[] path = {dir.toUri().toURL()};
        ClassLoadingMXBean classes = ManagementFactory.getClassLoadingMXBean();

        System.gc();
        long before = metaspaceKb();
        for (int i = 0; i < 2000; i++) {
            URLClassLoader loader = new URLClassLoader(path, null);  // one per "deployment"
            REGISTRY.add(loader.loadClass("Plugin").getConstructor().newInstance());
        }
        System.gc();
        System.out.printf("2,000 deployments kept: metaspace grew by about %,d KB, "
                + "classes loaded now %,d%n", (metaspaceKb() - before) / 100 * 100,
                classes.getLoadedClassCount() / 100 * 100);

        long unloadedBefore = classes.getUnloadedClassCount();
        REGISTRY.clear();                                   // the fix: drop the references
        System.gc();
        System.out.printf("after clearing the registry: %,d classes unloaded%n",
                classes.getUnloadedClassCount() - unloadedBefore);
    }
}

Output (G1; values rounded to hundreds):

Output
2,000 deployments kept: metaspace grew by about 2,700 KB, classes loaded now 4,600
after clearing the registry: 2,000 classes unloaded
  • Each deployment added a new copy of the same class, so the loaded class count rose by 2,000 and Metaspace grew by about 2,700 KB, roughly 1.4 KB for this almost empty class. Real applications load thousands of classes per deployment, so after a few redeployments the JVM fails with OutOfMemoryError: Metaspace if -XX:MaxMetaspaceSize is set, or grows without limit if it is not.
  • Once the registry let go of the instances, one collection unloaded all 2,000 classes. In real code the surviving reference is usually less obvious: a thread started by the plugin, a JDBC driver registered with DriverManager, a ThreadLocal, or a cache in a shared library.
  • A steadily rising loaded class count in jcmd <pid> VM.classloader_stats or a monitoring dashboard is the signature of this leak.

Common leak patterns and fixes

Typical Java memory leaks and their fixes
PatternFix
Static map or list used as a cache with no limitBounded cache with eviction, as above
Listeners or callbacks registered and never removedUnregister in a close() method, or hold listeners weakly
ThreadLocal values on pooled threadsremove() in a finally block; see ThreadLocal
Keys whose hashCode or equals change after insertionUse immutable keys, such as records
Class loaders kept alive after an application is redeployedStop threads and deregister drivers on shutdown
Unclosed streams, connections and result setstry-with-resources

Not every OutOfMemoryError is a leak: if the heap after GC is high but stable, the application simply needs more memory. For sizing, see JVM tuning.