In brief
You detect a memory leak in the JVM or .NET with an endurance test: typical load for many hours while you watch memory occupied after each full garbage collection. If that value keeps rising, something holds references to objects the application no longer needs. Two class histograms or heap dumps compared with each other point to the cause, and so does the path from the growing objects to a GC root, such as a static collection, an unbounded cache or an event listener that was never unregistered.
What a memory leak is when there is a garbage collector
In Java and .NET, memory is managed by the garbage collector (GC). It removes objects that are no longer reachable from the roots: static variables, thread stacks, handles. A memory leak in such an environment means objects the application no longer needs that are still reachable, so the GC cannot remove them. The Oracle documentation describes the result: such objects grow over time until they fill the heap or Metaspace, causing more frequent collections and eventually a java.lang.OutOfMemoryError.
A short load test will not show it. A leak of a few megabytes per hour is invisible in 30 minutes, yet after three days in production it stops the application. That is why leaks are hunted in an endurance test, described in the article on load, stress and endurance testing.
The most common causes in enterprise systems
- Unbounded cache. An in-memory map that receives every customer or every query, with no limit and no expiry. More on limits in the article on application caching.
- Static collections and registries. A list of "recent events" that is never cleared.
- Event listeners. In .NET an object subscribed to an event of a long-lived object (`+=` without `-=`) lives as long as the publisher. In Java the same applies to listeners and callbacks.
- ThreadLocal and context in thread pools. A pooled thread never ends, so data attached to it stays forever.
- Unclosed resources. Streams, result sets and connections that never return to the pool. A growing number of active connections is another symptom, as we describe in the article on database connection pools.
- Class loading. Repeated redeployments on the same application server or classes generated at runtime fill Metaspace.
- Native memory. Off-heap buffers, native libraries and threads use memory that heap tools cannot see.
How to design an endurance test for leaks
- Duration. At least several hours, and for systems running around the clock, also through the batch window. The slower the leak, the longer the test.
- Load. Typical, not peak, with the full mix of business paths. A leak often sits in one rare path, such as a report export.
- The right measure. Not total heap usage, which always draws a sawtooth, but memory occupied right after a full collection. A healthy application gives a flat line of sawtooth troughs; a leak gives a rising one.
- Process memory next to the heap. Compare the heap with the memory of the whole process. If the process grows while the heap stays flat, look at native memory.
- Collection frequency and duration. More frequent full collections and longer pauses are a warning before an OutOfMemoryError appears.
- Two measurement points. Take a class histogram or heap dump after warm-up and another after several hours. The cause shows up in the difference.
Containers add a memory limit. The Kubernetes documentation explains that when a container exceeds its memory limit, the kernel may kill it (OOM kill). Such a process disappears without an exception in the application log, so the test must also watch pod restarts and their termination reason.
Tools for the JVM
The jcmd command in the JDK provides most of what you need from a running process:
jcmd <pid> GC.class_histogram
jcmd <pid> GC.heap_dump /tmp/app.hprof
jcmd <pid> VM.native_memory summaryGC.class_histogram shows the number and size of objects per class. Two histograms taken a few hours apart usually point to the class that grows. GC.heap_dump writes a heap dump in HPROF format for analysis in a tool such as Eclipse MAT or JDK Mission Control. The jcmd documentation marks both commands as high impact, depending on heap size, so in a test you run them deliberately, and in production preferably on an instance taken out of traffic.
The `-XX:+HeapDumpOnOutOfMemoryError` option writes a dump at the moment of failure, so keep it enabled in the endurance test environment. Native Memory Tracking (`-XX:NativeMemoryTracking=summary`) tracks native memory allocated by the JVM itself, and Flight Recorder collects allocation and GC data with low overhead, as covered in the article on profiling applications in production.
Tools for .NET
Microsoft provides three command-line tools that run on Windows, Linux and macOS:
| Tool | What it is for | What to watch out for |
|---|---|---|
| dotnet-counters | continuous view of runtime counters: heap size per generation, collection count, allocations | lightweight, fine for the whole test |
| dotnet-gcdump | managed heap dump: object types, counts, sizes | forces a full generation 2 collection, which can pause a process with a large heap for a long time |
| dotnet-dump | full process dump and analysis with SOS commands | the dump is large and contains in-memory data, including personal data |
Microsoft's tutorial on debugging a memory leak follows this path: dotnet-counters shows a growing heap, dotnet-dump collects a dump, `dumpheap -stat` identifies the type with the most objects, and `gcroot` shows which root holds a chosen object. That last answer usually points straight to the place in the code.
Memory dumps contain the data the application was processing, so in an environment with production data treat them like a copy of the database: access control, encryption and deletion after analysis. An example of performance testing with long runs before a change in a billing system is the project on performance testing a billing system.
Questions and answers
How long should an endurance test run to detect a leak?
Long enough for post-GC memory growth to be clearly larger than normal fluctuation. For many applications several to a dozen or so hours is enough; for systems running around the clock, cover a full daily cycle with batch jobs. If the trend rises but slowly, extend the test rather than guessing.
Is growing memory usage always a leak?
No. The heap grows after startup as the application loads classes and fills caches, and then it should level off. A leak is growth that does not stop under constant load. The deciding measure is memory occupied after a full collection over successive hours of the test, not a single reading.
Does increasing the heap size fix a leak?
It only postpones the failure and lengthens GC pauses. A bigger heap makes sense when the application needs more memory at a stable level. With a leak you have to find the object that grows and the reference that holds it, because otherwise the problem returns after a few days.
Can I take a heap dump in production?
Yes, but carefully. A dump pauses the process for a time proportional to the heap size and writes a file with customer data. It is safer to take the instance out of traffic, take the dump, move the file to a protected location and delete it after analysis. Class histograms and counters are a lighter alternative.