Heap Dump Analysis: Finding Memory Leaks with MAT, VisualVM
Complete guide to JVM heap dump analysis using Eclipse MAT, VisualVM, and YourKit for identifying memory leaks and optimization opportunities.
Complete guide to JVM heap dump analysis using Eclipse MAT, VisualVM, and YourKit for identifying memory leaks and optimization opportunities.
Heap Dump Analysis: Detecting Memory Leaks with MAT, VisualVM, and YourKit
Heap dumps capture objects in the Java heap at a specific moment. They help explain memory leaks, unexpected object retention, and some OutOfMemoryError failures, but they do not capture all native memory used by the process.
This guide covers three tools for heap dump analysis. Eclipse Memory Analyzer (MAT) is free and provides retained-size and GC-root views. VisualVM is distributed as a standalone tool; YourKit is a commercial profiler with heap and allocation views.
Introduction
Heap dumps show Java heap objects and their references at capture time. They are useful when allocation profiling cannot explain why memory stays in use, when an OutOfMemoryError has no clear cause, or when you need to find which objects retain other objects. They do not show the history of how those objects accumulated, so compare dumps or use a recording when growth over time matters.
This guide uses Eclipse Memory Analyzer (MAT) 1.17.0 for the detailed workflow. VisualVM can handle quick inspections, while YourKit is a commercial option with allocation-site views. Check each tool’s release notes when its menus or supported dump formats differ from the steps here.
The capture commands below target JDK 25. Heap dumps can be very large and can expose sensitive data, so decide where the file will go and who can read it before you start a capture.
When to Use Heap Dump Analysis / When Not to Use
Heap dumps are useful when you need to understand why memory is not being released, investigate an OutOfMemoryError, or find what is retaining objects that should have been collected.
Avoid a manual dump when the JVM is already near its resource limit: the capture can take time, need substantial disk space, and make an incident worse. For performance issues that are not memory-related, use a recording or profiler instead.
Capturing a heap dump can trigger a full garbage collection and a long pause. JDK 25 documents GC.heap_dump as a high-impact diagnostic command whose impact depends on heap size and contents. The -XX:+HeapDumpOnOutOfMemoryError flag has no normal runtime cost while enabled, but the dump itself still uses time and disk when an error occurs. Test the capture path on a replica when possible, and leave enough free disk for a dump before enabling automatic capture.
Production safety: A heap dump may contain passwords, session tokens, personal data, and application state. Capture to a restricted directory, encrypt the file at rest and during transfer, record an owner and deletion date, and remove temporary copies after analysis. Use a replica for capture tests when one can reproduce the issue.
Heap Dump Architecture
graph TD
subgraph "JVM Heap"
subgraph "Object Instances"
O1[MyService<br/>1 instance<br/>256MB retained]
O2[Cache<br/>1 instance<br/>128MB retained]
O3[Connection Pool<br/>1 instance<br/>64MB retained]
end
subgraph "Reference Chains"
O1 --> O2
O2 --> O3
end
end
subgraph "Heap Dump Tools"
MAT[Eclipse MAT<br/>Dominator Tree<br/>Leak Suspects]
VV[VisualVM<br/>Heap Summary<br/>OQL Queries]
YK[YourKit<br/>Allocation Sites<br/>Retained Sets]
end
O1 -->|"Analyze"| MAT
O2 -->|"Analyze"| VV
O3 -->|"Analyze"| YK
Each tool has a different interface. MAT provides dominator trees and leak suspect reports. VisualVM includes a heap viewer and OQL console. YourKit can show object-retention and allocation-site views. Check the version-specific documentation for menus and supported dump formats.
Capturing Heap Dumps
Capture with jcmd (JDK 25)
Use jcmd from the same JDK version as the target JVM. The command below writes a compressed HPROF dump; adjust the destination to a directory with restricted access and enough free space. In JDK 25, jcmd expands %p in the filename to the target JVM’s PID. The shell inserts a UTC timestamp, and -gz=1 writes gzip-compressed output, so the filename ends in .hprof.gz.
# JDK 25; run as the account that owns the target JVM
PID=12345 # replace with the target JVM's PID
DUMP_FILE="/secure/heapdumps/heapdump-$(date -u +%Y%m%dT%H%M%SZ)-%p.hprof.gz"
jcmd "$PID" GC.heap_dump -gz=1 "$DUMP_FILE"
In JDK 25, this command requests a full GC before writing the dump unless you pass -all, which includes unreachable objects. A full GC can pause the application, and the dump operation is rated high impact. -gz=1 reduces file size with the fastest supported compression level; it does not remove sensitive data. Check the command’s exact options with jcmd <pid> help GC.heap_dump on the same JDK build.
Dump size depends on the live set, object graph, and compression. Do not estimate it from -Xmx alone. Check free space and test the capture duration and disk usage against a replica before relying on it during an incident.
Automatic Dump on OutOfMemoryError
# JDK 25: write an automatic dump to a restricted, pre-provisioned directory
java -XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/secure/heapdumps/java_pid%p.hprof \
-Xmx2g -jar your-application.jar
HotSpot JDK 25 has no -XX:HeapDumpSize option. Provision for the dump size your workload can produce and apply a retention policy outside the JVM. The automatic dump is written when a Java-heap OutOfMemoryError occurs, so it may not help with other resource failures.
Eclipse Memory Analyzer (MAT)
This walkthrough targets MAT 1.17.0. Its Dominator Tree shows which objects retain the most memory and helps trace why they remain reachable.
Key Views
MAT has several views and picking the right one early saves time.
The Leak Suspect Report is a useful first pass. It ranks possible memory-retention issues and shows retained size, relevant objects, and paths to GC roots. Treat its findings as leads to verify in the dump, not proof of a leak.
Dominator Tree is where you go for ownership chains. Object A dominates object B if every path from a GC root to B passes through A, which means A is the nearest ancestor keeping B alive. The tree arranges objects by dominance, so the biggest retained objects sit at the top level. Click any object to expand its children. Use this when you need to trace exactly which owner holds other objects.
Histogram gives you a class-level overview. It lists all classes in the dump with counts and shallow heap sizes. Sort by retained heap to find the biggest memory consumers. Group by class loader to spot old classloader instances. The Histogram loads faster than the Dominator Tree on large dumps and works well for initial orientation.
Move between views as your analysis develops: start with Leak Suspect Report for direction, use Histogram for quick class-level scanning, and switch to Dominator Tree when you need to follow specific retention chains in detail.
MAT 1.17.0 analysis workflow
# Open the dump in Eclipse Memory Analyzer 1.17.0
# File -> Open Heap Dump -> select heapdump.hprof
# Run leak suspect report
# Right-click on heap dump in Heap Dump History -> "Leak Suspect Report"
In the leak suspect report, look for sections marked in red—they indicate problems. The “Shortest Paths to GC Roots” show why objects cannot be collected. The “Accumulated Objects” section shows which classes accumulate excessively.
VisualVM
VisualVM is distributed separately from current JDK releases. Its heap viewer is useful for quick inspections; MAT offers more detailed retained-size analysis for large dumps.
Key Features
VisualVM’s heap analysis has two main tools for different jobs.
Heapwalker is the main analysis interface. The Summary tab shows total heap usage, object counts by category, and top memory consumers. The Classes tab lists every loaded class sorted by instance count or memory footprint. Click a class to see its instances. From any instance, right-click and select “Paths to GC Roots” to trace why it stays in memory. The Threads tab shows thread-local object collections that may be leaking.
Heapwalker also has a “References” pane for any selected object, listing everything that holds a reference to it. This lets you dig into a specific leak suspect without writing OQL.
OQL Console gives you SQL-like access to the heap. The Object Query Language can pattern-match on object graphs in ways standard views cannot. You can find objects with specific field values, collections above a certain size, or classes matching arbitrary patterns. OQL shines when you have a hunch about what is leaking but the standard views are not showing it.
Practical flow: start with Heapwalker’s summary and classes for orientation. If you spot something suspicious, drill into its instances there. If the standard views are not surfacing the issue, switch to OQL for targeted searches.
Example OQL Queries
-- Find all ArrayList instances larger than 1000 elements
select a from java.util.ArrayList a where a.size > 1000
-- Find String instances containing specific text
select s from java.lang.String s where s.toString().indexOf("suspicious") >= 0
-- Find objects with retention over 10MB
select x from instanceof java.lang.Object x
where sizeof(x) > 10485760
YourKit
YourKit is a commercial profiler with views for navigating object relationships.
Key Capabilities
Allocation recording captures where objects were created, not just that they exist. When analyzing supported dumps, allocation sites can help connect retained objects to the code paths that created them.
Retained set view shows exactly what a specific object keeps alive. Unlike MAT’s dominator tree, YourKit shows the full set of objects that would be collected if a specific object were collected.
Compare heap dumps takes two dumps and shows what changed. Objects that grew in count indicate potential leaks. This is invaluable for confirming whether memory issues are resolved.
Production Failure Scenarios
Scenario 1: Static Cache Growing Unboundedly
An application cache stores data forever instead of evicting old entries. The heap dump shows ConcurrentHashMap or similar collection retaining millions of entries. The dominator tree shows the cache itself as the top retainer.
The solution is implementing eviction policies—LinkedHashMap with access-order eviction, WeakHashMap for reference-based eviction, or dedicated cache libraries like Caffeine that handle eviction automatically.
How to identify this from the dump. Open the Dominator Tree in MAT and sort by retained size. A cache near the top retaining hundreds of MB or more is the first signal. Switch to the Histogram view and group by class name—the ConcurrentHashMap or HashMap entry will show an unusually high instance count. Click through to the instance view and check the table array size; millions of entries with timestamps spread across months confirm the leak.
What the retention chain looks like. The chain is usually short: GC root (static field) → the cache map → its internal table array → individual entry nodes. MAT’s “Shortest Paths to GC Roots” from the map instance shows the static field holding it directly. The entries themselves hold keys and values—look for String keys that grow without bound or custom objects that accumulate.
Common culprits beyond the obvious. Beyond a static ConcurrentHashMap used as a naive cache, watch for static List<Map<K,V>> chains where entries are appended but never removed, static ThreadLocal<Map> where the map grows per thread, and caches backed by third-party libraries that do not enforce size limits by default. Some applications also hold caches in static final collections initialized at class load time with data loaded from external sources that grow over days or weeks.
Prevention patterns. Tie cache size to a maximum capacity using LinkedHashMap in access-order mode with removeEldestEntry, or use Caffeine (for JVM applications) which supports expire-after-write, expire-after-access, and size-based eviction out of the box. If you must use a ConcurrentHashMap as a cache, pair it with a ScheduledExecutorService that runs a cleanup task periodically, or use a WeakHashMap when values should be garbage collected when no other references exist.
Scenario 2: Classloader Memory Leak
After redeploying a web application, the old version’s classes remain in memory because something still references the old classloader. The heap dump shows classes from the old application still loaded.
This typically happens when static collections hold references to objects that should have been cleaned up. ThreadLocal values, static caches, and JMX MBeans are common culprits.
How classloader leaks differ from object leaks. Standard memory leaks involve objects retaining other objects. Classloader leaks involve the ClassLoader instance itself remaining reachable after the application should have unloaded it. Every class the old ClassLoader loaded stays in memory because the ClassLoader is the namespace for those classes. A single leaked ClassLoader can retain tens of thousands of class instances.
What the dump reveals. In MAT, run the “Unloading of classes” query under the OQL console, or search for ClassLoader instances in the Histogram. Classes from the old application appear with their original ClassLoader marked as a separate group. Use “Shortest Paths to GC Roots” from the old ClassLoader instance to find what keeps it alive. The chain typically ends at a static field, a ThreadLocal, or a registered MBean.
The ThreadLocal trap. ThreadLocal values live in thread-local maps. If a thread from the old application pool is reused by the new deployment, and that thread’s map still holds a value under the old ClassLoader’s key, the ClassLoader stays reachable. Call threadLocal.remove() in a finally block, or use ThreadLocal.set(null) before returning the thread to the pool. Frameworks like Tomcat and Jetty provide lifecycle hooks for this; make sure they are wired up.
The static collection trap. Static Map or Collection fields initialized during application startup can accumulate entries that reference old class instances. The pattern is: application starts, populates a static cache, the cache holds references keyed by class objects from the old ClassLoader. After redeployment, the new ClassLoader loads new class instances, but the static cache still holds the old class objects, keeping the old ClassLoader alive.
JMX MBean registration. MBeans registered in the platform MBeanServer during application startup hold a hard reference to the registering class’s ClassLoader. If the MBean is not unregistered during shutdown, the ClassLoader cannot be collected. The fix is to call MBeanServer.unregisterMBean() in a @PreDestroy method or equivalent shutdown hook.
Identifying classloader leaks in MAT. Use the “Class Loader Explorer” view if available, or search the Histogram for java.lang.ClassLoader instances grouped by defining classloader hash. ClassLoaders with a different hash from the current application ClassLoader are worth investigating further. Trace each one to its GC root to confirm.
Scenario 3: Connection Pool Leak
Database connection pools that do not return connections properly accumulate connections over time. The heap dump shows physical database connections held by connection pool proxies that the application never closed.
The “Paths to GC Roots” trace reveals where the leaked connections are held—typically in some business logic object that acquired the connection but failed to return it.
How to identify this from the dump. Open the Histogram in MAT and group by oracle.jdbc.driver.OracleConnection or your pool’s connection class. A high count of live connection instances is the first signal. Switch to the Instances view and open “Paths to GC Roots” for any connection. The chain usually ends at a business logic object that holds the connection as a field. Common holders include DAO classes with a Connection field set during a transaction and never cleared, thread pool tasks that capture a connection in a closure, or HTTP request handlers that store a connection while waiting for a dependent I/O operation to complete.
What the retention chain looks like. The chain typically runs GC root (thread stack variable or static field) to business logic object to connection pool proxy to physical database connection. The physical connection itself may hold additional state: prepared statements, temporary tables, or transaction locks that add to the memory cost. Some pool implementations cache prepared statements per connection, so a leaked connection can retain thousands of cached statements too.
Common culprits beyond the obvious. Watch for exception paths that skip connection return. If your code uses try-with-resources correctly, the leak is usually in framework code: connection pool wrappers that fail to return connections when an SQLException propagates up, or servlet filters that acquire a connection in doFilter() but throw before reaching the code that would return it. Some ORM frameworks hold connections in thread-local storage during nested transactions. If a nested operation throws, the outer transaction’s connection may not be returned. Connection leaks also hide inside connection pool validation threads. If the pool’s housekeeping thread holds a connection reference during a slow query, that connection is effectively leaked until the validation completes.
Prevention patterns. Always use try-with-resources for connections:
try (Connection conn = dataSource.getConnection()) {
// use connection
} // automatically closed and returned
If try-with-resources is not available, pair every getConnection() with a finally block that calls close(). For thread pool tasks, avoid capturing the connection in a lambda or anonymous class. Instead, acquire the connection inside the task’s run() method and close it before the method returns. For servlet filters and interceptors, wrap the connection acquisition in a filter that guarantees return regardless of what the filtered code throws. Some teams add a connection leak detection mode to their pool configuration, such as Druid’s removeAbandoned, which logs a stack trace when a connection is not returned within a configured timeout.
The pool exhaustion cascade. Connection pool leaks do not just waste memory, they cause outages. When connections leak faster than the pool can create new ones, the pool exhausts its maximum size. Subsequent requests block waiting for a connection, and the application stops handling requests. In MAT, this shows as all available connections held by leaked proxy objects. The fix is the same as for the leak itself, but you also need to increase the pool’s maxTotal and add monitoring on pool utilization to catch exhaustion before it cascades.
Trade-off Table
| Tool | Cost | Strength | Best For |
|---|---|---|---|
| Eclipse MAT | Free | Deep analysis, leak suspects | Production incident analysis |
| VisualVM | Free with JDK | Quick checks, OQL | Development debugging |
| YourKit | Commercial | Usability, allocation sites | Active development profiling |
Implementation Snippets
Analyzing Heap Dump Programmatically with MAT API
import org.eclipse.mat.*;
import org.eclipse.mat.query.*;
import org.eclipse.mat.snapshot.*;
import org.eclipse.mat.util.*;
public class HeapDumpAnalyzer {
public static void main(String[] args) throws Exception {
// Open heap dump
Snapshot snapshot = SnapshotFactory.openSnapshot(
"heapdump.hprof",
null);
// Get dominator tree
DominatorTree dominatorTree = snapshot.getDominatorTree();
// Find largest retained objects
ResultTable<?> result = dominatorTree.query(
"SELECT retainedSize, shallowSize, this, className "
+ "ORDER BY retainedSize DESC LIMIT 20");
for (Object row : result.getRows()) {
System.out.printf("Retained: %s, Shallow: %s, Class: %s%n",
formatSize(((Number) ((List<?>) row).get(0)).longValue()),
formatSize(((Number) ((List<?>) row).get(1)).longValue()),
row);
}
snapshot.dispose();
}
private static String formatSize(long bytes) {
if (bytes < 1024) return bytes + "B";
if (bytes < 1024 * 1024) return String.format("%.1fKB", bytes / 1024.0);
if (bytes < 1024 * 1024 * 1024) {
return String.format("%.1fMB", bytes / (1024.0 * 1024));
}
return String.format("%.1fGB", bytes / (1024.0 * 1024 * 1024));
}
}
Observability Checklist
Before concluding heap analysis, verify that the dump captured the relevant state, that you traced retention paths to GC roots, and that you separated a likely cause from a symptom. A default JDK 25 jcmd GC.heap_dump requests a full GC before capture; passing -all also includes unreachable objects.
Also confirm that multiple dumps show consistent patterns, that the objects you identified as leaks correlate with the time when memory usage grew, and that your fix actually addresses the root cause rather than symptoms.
Security and Compliance Notes
Heap dumps contain Java heap objects, including values that may be credentials, session tokens, personal data, or internal application state. Treat every dump as sensitive, even if you have not confirmed which values it contains.
Restrict read access to the incident team, encrypt the dump in storage and during transfer, and avoid attaching it to tickets or sending it through chat. Record who owns the artifact and when it must be deleted. Include replicas, analysis workstations, temporary files, and backups in the cleanup plan. For regulated workloads, follow the organization’s data-handling policy before capturing a dump.
When possible, reproduce the issue on a replica and test capture there first. If you must capture from a production instance, check free disk, choose one instance that can be removed from traffic if needed, and plan how the file will be transferred and deleted. Record the capture and cleanup in the incident log.
Common Pitfalls / Anti-Patterns
The biggest mistake is analyzing a dump from the wrong point in time. Capture when the memory trend shows the problem, while the process and host still have room to write the file. If the JVM is already critically stressed, use lower-impact diagnostics first or capture from a replica.
Another issue is confusing retained size with shallow size. Shallow size is the object itself. Retained size includes all objects that would be collected if the object were collected. Always look at retained size when diagnosing memory issues.
Not following references all the way to GC roots leads to fixing symptoms. An object might be held by another object, which is held by a third—keep tracing until you find the GC root.
Finally, forgetting that some leaks are in permanent generation or metaspace (classloaders, interned strings) before Java 8. These require different analysis approaches than heap dumps of Java heap.
Quick Recap Checklist
- Enable
-XX:+HeapDumpOnOutOfMemoryErroronly after checking disk capacity, access controls, and retention - Use MAT for deep analysis and leak suspect reports
- Use VisualVM for quick checks and OQL queries
- Use YourKit for allocation site analysis and intuitive navigation
- Always trace retention paths to GC roots
- Distinguish retained size from shallow size
- Encrypt heap dumps, restrict access, and set a deletion date
Interview Questions
Shallow heap is the size of the object itself—the memory consumed by its fields and object header. A String object has a shallow heap of roughly 48 bytes for the object itself, plus whatever its char[] array holds.
Retained heap is the total memory that would be freed if the object were garbage collected. It includes the shallow heap of the object plus the retained heaps of all objects it keeps alive, directly or indirectly. If a Map holds 10,000 entries, removing the Map frees those 10,000 entries too—the Map's retained heap includes them.
When diagnosing memory issues, always look at retained heap. A small object holding references to millions of large objects has a small shallow heap but enormous retained heap.
Start with a dump taken while the memory problem is visible and the host still has room to write the file. Open it in MAT and run the Leak Suspect Report, then check its findings in the Dominator Tree and paths to GC roots.
If the report does not pinpoint the issue, use the Dominator Tree. Sort by retained size to find the largest retained objects. For each large retainer, trace the shortest path to GC roots. This reveals what keeps the object alive.
Compare multiple dumps over time if possible. Objects that grow in count or retained size across dumps are likely leaks. The allocation site for growing objects tells you which code creates them.
GC roots are objects that the garbage collector assumes are live without examining references to them. They include thread stack variables, static variables from loaded classes, JNI references, and objects in the JVM internal handles.
Because GC roots are always considered live, anything they reference is also live, transitively. When tracing why an object cannot be collected, you trace to a GC root. The object cannot be freed because some GC root still reaches it.
Common GC root types: local variables in thread stacks, static fields of classes, JNI global references, objects in the string table, class objects from loaded classes, and JVM internal references.
Both tools can capture heap dumps. This guide uses the JDK 25 jcmd <pid> GC.heap_dump command because Oracle's current troubleshooting guide recommends it. Run diagnostic tools from the same JDK version as the target JVM and check that version's command options.
The JDK 25 command can request a full GC and is rated high impact. The -XX:+HeapDumpOnOutOfMemoryError option can capture automatically, but it still needs disk space and a secure destination when the dump is written.
The Leak Suspect report uses several algorithms to identify problematic memory retention. It calculates the retained size of all objects, then identifies groups of objects that together contribute significantly to memory usage.
For each suspected leak, the report shows the "shortest path to GC roots"—the minimum chain of references from a GC root to the suspect objects. This tells you exactly what keeps those objects alive. It also estimates how much memory would be freed if the leak were fixed.
The report is generated automatically using pattern matching against known leak patterns, statistical analysis of retention chains, and heap dump comparison against typical object graphs.
Heap dump analysis captures a point-in-time snapshot of all live objects. It shows what objects exist and what holds them, but does not show when they were created. Useful for finding what is retaining memory at the moment of the dump.
Allocation profiling records where objects are created over time. It shows which code paths allocate the most objects, which is different from showing what retains them. Allocation profiling is better for identifying leak sources (where they are created), while heap dumps are better for identifying leak sink (what holds them).
In the dominator tree, object A dominates object B if every path from any GC root to B passes through A. This means if A is collected, B would also become unreachable. The dominator tree shows ownership—each object's immediate dominator is its "parent" in the retention chain.
The biggest retained objects appear at the top level of the dominator tree (not dominated by anything larger). Use this to find the "owner" objects that cause other objects to be retained.
Heap dumps capture only live objects at a single moment in time. They do not show historical growth patterns—for that you need multiple dumps over time. Heap dumps also do not capture object allocation sites by default; you need YourKit or JMC for that.
Taking a heap dump itself can cause a long stop-the-world pause, especially with large heaps. This can worsen production incidents if triggered manually. Also, heap dumps do not include information about object fields that were garbage collected before the dump.
Metaspace is separate from the Java heap, but classloader instances and their associated metadata appear in heap dumps. Look for ClassLoader instances in the heap dump. For Classloader leaks, trace from the Classloader to all classes it loaded, then find what keeps the Classloader alive.
The leak pattern after web application redeployments is the old Classloader still referenced by something (usually ThreadLocal or a static cache). MAT's "Shortest Paths to GC Roots" from the Classloader reveals what is keeping it alive.
OQL (Object Query Language) is a SQL-like language for querying heap dumps in VisualVM. You can use it to find objects with specific characteristics, such as all Strings containing certain text, collections over a certain size, or objects with particular field values.
Example: select s from java.lang.String s where s.toString().indexOf("password") >= 0 finds strings potentially containing passwords. OQL is powerful for ad-hoc analysis when the standard views do not surface the issue.
String.intern() pools strings in the JVM string table. A leak pattern occurs when code interns strings that should not be interned, causing the string table (which is a GC root) to retain unlimited strings. In the heap dump, look for String instances with unexpectedly high retained set counts.
Large char[] arrays that back Strings with repeated content can indicate interning issues. Finding the source of incorrectly interned strings involves tracing from the string pool to what keeps those strings alive.
With JDK 25, the default jcmd <pid> GC.heap_dump filename.hprof requests a full GC before writing the dump. Use -all to include unreachable objects as well. The default is often more useful for retention analysis, but the GC and dump can pause the application.
Object churn is historical information and cannot be inferred from one dump. Use a recording or compare captures taken at different times to study growth.
YourKit's comparison feature takes two heap dumps from different points in time and shows what changed between them. It groups changes into "new objects," "removed objects," and "changed objects" categories. New objects that grow in count indicate potential leaks.
The comparison shows allocation sites for new objects, helping you trace leaks back to their source code. This is invaluable for confirming whether a memory issue is resolved after code changes.
Native memory leaks come from direct ByteBuffers (using native memory outside the heap), JNI code, memory-mapped files, and JVM internal structures like the code cache. These do not appear in Java heap dumps.
Diagnose with -XX:NativeMemoryTracking=detail and jcmd <pid> VM.native_memory summary. For direct ByteBuffer leaks, look for phantom references to ByteBuffers that are not being cleaned up by the garbage collector.
For a very large heap, budget disk and analysis-machine memory before capture. MAT's memory needs depend on the dump and analysis; there is no fixed rule that it needs a particular percentage of the dump size. Check the release notes for your MAT version and try the workflow on a representative dump first.
If a full dump is too risky, collect a class histogram or a Java Flight Recording first. These may narrow the problem, though they do not replace object-retention paths when you need to find what is keeping objects alive.
For collections, shallow heap is the size of the collection object itself plus the size of the backing array or internal structure. Retained heap includes all elements the collection holds, transitively. A HashMap with 10,000 entries has small shallow heap but enormous retained heap.
When analyzing collection leaks, always look at retained heap to understand the true memory impact of the collection staying in memory.
Allocation sites show where objects were created. In YourKit or JMC, right-click a leaking object and select "Show Allocation Stack Trace." This reveals the exact code path that created the leaking objects. Combined with retention analysis, you get both where they were created and what holds them.
Common patterns: objects created in one layer but retained in another, caches without eviction, or builders that accumulate results without releasing references.
Shallow heap tells you the base cost of an object if it were the only thing in memory. Retained heap tells you the actual memory impact of keeping that object alive. A small object holding a reference to a large cache has small shallow heap but large retained heap.
When deciding what to fix, prioritize high retained heap objects because fixing them frees the most memory.
Classloader leaks appear as classes from old application versions still being loaded after redeployment. In MAT, find ClassLoader instances and trace what keeps them alive—usually ThreadLocal values, static caches, or JMX MBeans registered by the old application.
In application servers, ensure implementations properly implement lifecycle methods (destroy, stop) to clean up references. Use the "Unloading of classes" view in MAT to see if classes are being unloaded properly.
The most common sources: unbounded caches (ConcurrentHashMap used as cache without eviction), static collections holding references, ThreadLocal values not removed, unclosed resources (streams, connections), finalizers creating references, and classloader leaks in application servers. Memory leak patterns also include listener registrations not removed, callback accumulation in event systems, and static factory instances holding references.
Systematic approach: take two heap dumps at interval, compare objects that grew, trace their retention paths to GC roots.
Further Reading
- Java Mission Control — JFR-based heap analysis with allocation sites
- GC Logging Analysis — Correlate memory patterns with GC events
- JVM heap layout and object headers — How heap regions, generations, and object layout vary by runtime
- Heap walking and allocation tracking — When to use allocation profiling, heap walking, or native-memory tracking
- Eclipse MAT 1.17.0 — Official downloads and documentation; check the release notes for UI changes
- VisualVM — Standalone downloads and current release notes
- Oracle JDK 25 diagnostic tools — Includes
jcmdusage and heap-dump impact - Oracle JDK 25
jcmdreference — SupportedGC.heap_dumpoptions - JEP 241: Remove the jhat Tool — Why
jhatis no longer included in the JDK - Advanced Java & JVM Internals Roadmap — Parent roadmap
Conclusion
Heap dumps help answer why Java objects remain reachable, while recordings and profilers show how memory use changes over time. For JDK 25, start with the documented jcmd GC.heap_dump command or configure automatic capture only after checking disk capacity and artifact handling. MAT 1.17.0 provides the workflow shown here; VisualVM and YourKit offer other ways to inspect a dump.
Capture while the system can still write the file, then trace retention paths to GC roots and compare retained size with shallow size. Keep the dump encrypted, access-controlled, and scheduled for deletion; it may contain data from the application’s live heap.
Category
Related Posts
Async-Profiler: A Practical JVM Profiling Guide
Choose CPU, allocation, lock, or live-object profiling, then compare JVM profiles under a repeatable workload without guessing at overhead.
Java atomics and VarHandle: Concurrency in Java 25
Learn Java 25 atomics: AtomicInteger, AtomicReference, CAS loops, LongAdder, VarHandle memory modes, and when to choose an atomic or lock.
JVM Bytecode Verification: Type Checking and Stack Map Frames
A practical guide to JVM bytecode verification by class-file version, including type inference, StackMapTable frames, VerifyError debugging, and verification limits.