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.
Contents
What a memory leak is in Java
In C, a leak is memory that was allocated and never freed. Java has no free
Two sizes matter when looking for the cause. An object's shallow size is its own memory: an ArrayList
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
| Tool | Since | Shows | Best for |
|---|---|---|---|
GC logs, MemoryMXBean | JDK 9 (-Xlog | Heap used after each collection | Noticing that a leak exists |
jcmd <pid> GC.class_histogram | JDK 7 | Live instances and bytes per class | A quick look at what is growing |
-XX:+HeapDumpOnOutOfMemoryErrorjcmd GC.heap_dump | JDK 6 and earlier, JDK 7 | Every object and reference | Finding the retaining field |
| Eclipse MAT, VisualVM | Separate tools | Dominator tree, paths to roots | Analysing heap dumps |
JFR event jdk.OldObjectSample | JDK 11 in OpenJDK | Sampled live objects with allocation site and root path | Production, where a full dump is too big |
| Native Memory Tracking | JDK 8 | Memory outside the heap | Metaspace, threads, direct buffers |
The programs were run on JDK 25. Several of them call System.gc()
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
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:
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 (
) dominate with about 52 MB, which says what is filling the heap but not why, since everything uses byte arrays.[B - The useful clue is further down: exactly 5,000
objects after 5,000 requests, held inLeakingCache$Session 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.HashMap$Node
The FillerElement
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.
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:
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
- Leak Suspects report (MAT): names the objects that retain most of the heap. Here it would point at the
holding 6,000+ arrays.ArrayList - 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.
- 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
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
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:
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
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.ORDERS.add - The reference chain reads bottom to top as the path to the leak: a
is an element of anlong[] , which is theObject[] field of anelementData , which is the static fieldArrayList 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 runningORDERS method.main - In production, start a recording with
, dump it withjcmd <pid> JFR.start settings=profile , and open it in JDK Mission Control, whose memory leak view shows the same chains. Seejcmd <pid> JFR.dump filename=app.jfr path-to-gc-roots=trueJava Flight Recorder .
The fix: bound the collection
The fix is to give the cache a limit. A LinkedHashMapremoveEldestEntry
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:
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
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:
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
and calling it in the screen'sregister left 0. Weak references are another option, but they make listener lifetimes depend on the collector, which is harder to reason about.close() - Each key's
was changed afterid , soput 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.remove - 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
in aremove() block, or usefinallyscoped 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
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):
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
ifOutOfMemoryError: Metaspace is set, or grows without limit if it is not.-XX:MaxMetaspaceSize - 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
, aDriverManager , or a cache in a shared library.ThreadLocal - A steadily rising loaded class count in
or a monitoring dashboard is the signature of this leak.jcmd <pid> VM.classloader_stats
Common leak patterns and fixes
| Pattern | Fix |
|---|---|
| Static map or list used as a cache with no limit | Bounded cache with eviction, as above |
| Listeners or callbacks registered and never removed | Unregister in a close() |
ThreadLocal | remove()finally |
Keys whose hashCodeequals | Use immutable keys, such as records |
| Class loaders kept alive after an application is redeployed | Stop threads and deregister drivers on shutdown |
| Unclosed streams, connections and result sets | try-with-resources |
Not every OutOfMemoryError