A practical guide to Java memory leak detection with VisualVM
A Java memory leak occurs when objects are no longer useful but remain reachable from live references. The garbage collector cannot reclaim them, so heap usage gradually rises until the application spends excessive time collecting memory or fails with an OutOfMemoryError.
VisualVM provides a practical way to investigate this behaviour without immediately reaching for a commercial profiler. It can connect to a running JVM, display heap and thread activity, create heap dumps, and compare object usage before and after garbage collection.
This matters in production systems such as Spring APIs, JDBC services and batch applications. A service running smoothly in a developer environment may behave very differently during an EOFY reporting rush, when Australian customers upload large files or send a sudden wave of requests from Sydney, Melbourne and Brisbane.
Recognise the signs of a leak
The clearest warning sign is a saw-tooth memory graph that rises after each garbage collection instead of returning to a stable baseline. A temporary workload spike is normal; a steadily increasing post-GC baseline is not.
Other symptoms include longer pauses, slower API responses, frequent full collections and growing container memory usage. Check application logs for messages such as GC overhead limit exceeded or Java heap space. Before opening VisualVM, record the Java version, heap settings, deployment mode and the operation that triggers the suspected leak.
A leak may be caused by static collections, unbounded caches, listeners that are never removed, ThreadLocal values, retained HTTP sessions or application objects accidentally stored in a singleton. Database connection pools and ORM sessions can also create pressure when resources are not closed correctly.
Connect VisualVM to the JVM
Install a VisualVM release compatible with the Java runtime used by the application. Start the target service with useful monitoring options, then open VisualVM and select the process under Local. A local process usually exposes monitoring data automatically when both tools have suitable permissions.
The Monitor tab shows heap, metaspace, classes and threads. Watch the heap after a full workload cycle and use the garbage-collection control carefully in a non-production environment. The Sampler tab is a low-overhead first step for seeing which classes occupy memory; the Profiler gives deeper detail but can impose more overhead.
For a remote JVM, enable JMX securely rather than exposing an unauthenticated management port to the internet. In an Australian cloud deployment, an application hosted in an AWS Sydney region may be several network hops away from a developer in Perth, so firewall rules, VPN access and connection latency need to be considered.
Capture and compare heap dumps
When the post-GC baseline keeps increasing, open the Monitor tab and create a heap dump. A dump can be large, so check available disk space first. For a containerised service, write it to a mounted volume rather than the container’s short-lived filesystem.
Open the dump in VisualVM and inspect Classes, Instances and the biggest objects. The useful question is not simply “which class is largest?” but “what is retaining these objects?” Look for paths from a GC root, such as a static field, active thread, class loader or long-lived framework component.
For example, a CSV upload endpoint may create a list containing every parsed row instead of processing records incrementally. Testing that endpoint alongside a CSV upload guide can help reproduce the workload while you compare heap dumps before and after several uploads.
| VisualVM view | What it reveals | Useful interpretation |
|---|---|---|
| Monitor | Heap and GC trends | A rising post-GC baseline suggests retention |
| Sampler | Live object counts and sizes | Identifies classes growing during a workload |
| Heap dump | Object instances and references | Shows likely retaining paths |
| Threads | Thread count and states | Exposes stuck tasks or thread-local retention |
| Classes | Loaded class counts | Growth may indicate class-loader leaks |
Trace common retention patterns
Static maps and caches are frequent causes of leaks. A cache without an eviction policy grows with every customer, request or uploaded record. Replace it with a bounded cache, use expiry where appropriate, and confirm that keys do not accidentally retain large object graphs.
Thread pools deserve special attention. A worker thread may live for the entire application lifetime, keeping a ThreadLocal value reachable long after a request finishes. Always clear request-specific data in a finally block. Similarly, unregister listeners and shut down executors when application contexts are closed.
Spring and Hibernate can make retention harder to spot because proxies, persistence contexts and framework collections appear between the root and the business object. Inspect the reference chain patiently, then verify whether the object is genuinely required or merely being held by an overly broad scope.
Verify the fix under realistic load
After changing the code, repeat the same workload and capture another pair of heap dumps. Compare the number of retained instances and the post-GC baseline rather than relying on a single screenshot. A successful fix should show stable memory after warm-up, even if total usage is higher than before.
Use realistic Australian traffic patterns where possible: an online retailer may receive concentrated evening activity, while a government or finance integration may experience heavy batch traffic around local business deadlines. Test uploads, authentication flows, scheduled jobs and database queries together because leaks often appear through interactions between components.
Keep heap-dump files protected because they can contain customer names, email addresses, tokens and other sensitive information. Remove them from shared folders after analysis and avoid collecting production data casually. VisualVM can locate the symptom, but disciplined workload reproduction and careful reference analysis are what turn that evidence into a reliable fix.