Understanding and Debugging Java Memory Leaks
Memory management is one of the responsibilities handled automatically by the Java Virtual Machine (JVM). Unlike languages such as C and C++, where developers often allocate and release memory manually, Java uses garbage collection to identify objects that are no longer reachable and reclaim the memory they occupy. This reduces the amount of manual memory management required, but it does not mean Java applications are immune to memory leaks.
A Java memory leak occurs when an application retains references to objects that are no longer needed. Because these objects remain reachable from the application, the garbage collector cannot remove them, even when they no longer serve any useful purpose. As the application continues running, the number of retained objects can increase until the available heap memory becomes insufficient. This can lead to increased garbage collection activity, slower application response times, and eventually an OutOfMemoryError.
Memory leaks are not always easy to identify because an application can run normally for hours or even days before the problem becomes noticeable. A service might initially use a small amount of memory, but its heap consumption gradually increases as requests are processed. Restarting the application may temporarily resolve the issue, but the memory consumption eventually returns.
In this article, we will explore how to diagnose and fix a Java heap memory leak using tools included with the JDK and Eclipse Memory Analyzer (MAT).
1. Understanding Java Memory Leaks
Before investigating a memory leak, it is important to understand how Java manages memory and why objects sometimes remain in the heap longer than expected. The JVM allocates memory for objects created by an application. When an object is no longer reachable through any active reference, it becomes eligible for garbage collection. The garbage collector can then reclaim the memory occupied by that object.
Consider the following example:
public class MemoryExample {
public static void main(String[] args) {
createObject();
}
private static void createObject() {
String message = new String("Hello Java");
}
}
The message variable references a newly created String object. When the createObject() method finishes executing, its local variable is no longer accessible. Assuming no other references exist, the object becomes eligible for garbage collection.
Now consider a different implementation:
import java.util.ArrayList;
import java.util.List;
public class MemoryLeakExample {
private static final List<byte[]> CACHE = new ArrayList<>();
public static void main(String[] args) {
while (true) {
byte[] data = new byte[1024 * 1024];
CACHE.add(data);
}
}
}
In this example, the application continuously creates byte arrays, each approximately 1 MB in size, and stores them in a static collection. Although the application might no longer need the individual arrays after adding them to the collection, the static CACHE reference continues to hold them. Since the arrays remain reachable, the garbage collector cannot reclaim their memory. As the collection grows, the application consumes more heap memory until it eventually runs out of available space.
This illustrates an important characteristic of Java memory leaks: the problem is not necessarily that memory cannot be reclaimed, but that the application continues to hold references to objects that should have been released.
2. Heap Memory and Native Memory: Understanding the Difference
When investigating memory consumption in a Java application, it is important to distinguish between heap memory and native memory. Although both contribute to a JVM process’s overall memory footprint, they serve different purposes and require different diagnostic approaches.
2.1 Java Heap Memory
The Java heap is the memory area where the JVM allocates most Java objects and arrays. The garbage collector manages it, identifying objects that are no longer reachable and reclaiming their memory. For example:
Employee employee = new Employee();
When this statement executes, the Employee object is allocated on the Java heap. The local variable employee holds a reference to that object. If the reference is removed and no other references point to the object, it becomes eligible for garbage collection.
A heap memory leak occurs when objects remain reachable even though the application no longer needs them. Common causes include:
- Static collections that continuously accumulate objects.
- Caches without eviction policies or size limits.
- Event listeners that are registered but never removed.
- ThreadLocal variables that retain objects longer than expected.
- Collections that hold references to completed tasks or requests.
- Long-lived objects that unnecessarily retain large object graphs.
Heap memory can be investigated using garbage collection logs, heap dumps, and tools such as Eclipse Memory Analyzer.
2.2 Native Memory
Native memory refers to memory allocated outside the Java heap. It is used by the JVM itself and by native components that support application execution. Examples include:
- Thread stacks used by JVM threads.
- Direct byte buffers allocated outside the Java heap.
- JIT compiler and code cache memory.
- JVM internal data structures.
- Native libraries accessed through JNI.
- Memory allocated by third-party native components.
Consider the following example:
import java.nio.ByteBuffer;
public class NativeMemoryExample {
public static void main(String[] args) {
while (true) {
ByteBuffer buffer =
ByteBuffer.allocateDirect(10 * 1024 * 1024);
}
}
}
The allocateDirect() method creates a direct byte buffer whose storage is allocated outside the regular Java heap. Although the buffer object itself is represented by a Java object on the heap, its underlying memory is allocated in native memory. Direct buffers are managed differently from ordinary Java objects. Their native storage is generally released when the associated buffer becomes eligible for cleanup, but retaining references to direct buffers can cause native memory consumption to increase.
Native memory problems can also occur when JNI code allocates memory without releasing it properly.
2.3 Comparing Heap and Native Memory
| Characteristics | Heap Memory | Native Memory |
|---|---|---|
| Allocation | Java Objects and arrays | JVM and native components |
| Management | Garbage collector | JVM, native libraries and operating system |
| Examples | Objects, collections, arrays | Thread stacks, direct buffers, JNI allocations |
| Diagnostic tools | Heap dumps, MAT, jcmd | Native Memory Tracking, OS tools |
| Common problems | Retained objects, unbounded caches | Native allocation leaks, excessive threads, direct buffer retention |
One important distinction is that the total memory consumed by a Java process is not limited to its configured heap size. A JVM with a maximum heap of 2 GB can consume considerably more than 2 GB of physical or virtual memory because it also requires native memory. This distinction becomes important when an application appears to consume excessive memory but its heap usage remains relatively stable.
3. Tools for Investigating Java Memory Leaks
Java provides several diagnostic tools that help developers understand memory consumption, inspect JVM processes, generate heap dumps, and investigate object retention. In this article’s exercise, we will primarily use jcmd and Eclipse Memory Analyzer (MAT). However, it is useful to understand the other tools available.
3.1 jcmd
jcmd is a diagnostic utility included with the JDK. It allows developers to send diagnostic commands to a running JVM process. It can provide information about heap usage, garbage collection, JVM configuration, thread activity, and other runtime characteristics. Some useful commands include:
jcmd -l
Lists running Java processes and their process identifiers.
jcmd <pid> GC.heap_info
Displays information about the Java heap, including its current capacity and usage.
jcmd <pid> GC.heap_dump heapdump.hprof
Creates a heap dump containing information about objects currently in the Java heap.
The heap dump can then be opened using a memory analysis tool to investigate object references and memory retention.
3.2 Eclipse Memory Analyzer (MAT)
Eclipse Memory Analyzer (MAT) is an open-source tool for analysing Java heap dumps. It helps developers understand how memory is being used and identify objects that prevent other objects from being garbage collected. MAT provides several features for investigating memory problems:
- Dominator Tree: Identifies objects that dominate other objects in the heap and helps locate the structures retaining large amounts of memory.
- Leak Suspects Report: Analyses a heap dump and highlights potential memory leak sources.
- Histogram: Displays the number of instances of each class and their memory consumption.
- Retained Heap: Shows the amount of memory that would become collectible if a particular object were removed.
- Path to GC Roots: Shows the reference chain keeping an object reachable.
One of the most useful features is the Dominator Tree. It helps developers identify which objects are retaining large portions of the heap rather than simply showing which classes occupy the most memory. MAT can be downloaded from the official Eclipse Memory Analyzer website.
3.3 Java Flight Recorder (JFR) and Java Mission Control (JMC)
Java Flight Recorder (JFR) is a low-overhead profiling and diagnostic framework built into the JVM. It records runtime events, including object allocations, garbage collection activity, thread behaviour, and CPU usage.
Java Mission Control (JMC) provides a graphical interface for analysing recordings generated by JFR. These tools are useful when investigating memory problems that occur over time. Rather than relying only on a heap dump, developers can examine allocation patterns and identify which parts of an application create the most objects.
3.4 Native Memory Tracking (NMT)
Native Memory Tracking is a JVM feature that tracks memory allocated by the JVM through its internal native memory allocation mechanisms. It can help determine whether native memory consumption is increasing and which JVM subsystems account for that usage. NMT must be enabled when the JVM starts:
java -XX:NativeMemoryTracking=summary \
-XX:+UnlockDiagnosticVMOptions \
-jar application.jar
Once the application is running, we can inspect native memory usage:
jcmd <pid> VM.native_memory summary
To compare memory consumption at different points in time, we can also use:
jcmd <pid> VM.native_memory baseline
After taking a baseline, execute:
jcmd VM.native_memory summary.diff
This displays changes in tracked native memory allocations since the baseline. NMT is useful for diagnosing JVM native memory consumption, but it does not track every native allocation made by third-party libraries or arbitrary native code.
3.5 Other Useful Diagnostic Tools
Other tools can also help investigate memory problems:
| Tool | Purpose |
|---|---|
jstat | Monitors garbage collection statistics and heap usage. |
jmap | Provides heap-related diagnostic operations and can generate heap dumps. |
| VisualVM | Provides graphical monitoring, profiling and heap analysis. |
| Operating system tools | Monitor process memory, threads and system-level resource consumption. |
These tools complement one another. For example, jstat can help identify increasing garbage collection activity, while MAT can reveal which objects are responsible for retaining memory.
4. A Practical Workflow for Debugging a Java Memory Leak
Identifying a memory leak requires more than looking at the amount of memory consumed by an application. A Java application may legitimately use more memory as it processes additional requests, loads data, or builds caches. The objective is to determine whether memory consumption is growing unexpectedly and identify the objects responsible for that growth. We will follow an approach where we start with confirming the memory problem and end with validating the fix.
4.1 Establish Whether Memory Consumption Is Actually Increasing
The first step is to determine whether the application is experiencing a memory problem. An application consuming a large amount of memory does not automatically indicate a memory leak. For example, an application may allocate many temporary objects while processing requests. The garbage collector eventually reclaims those objects, allowing memory usage to stabilise. A more concerning pattern occurs when memory consumption continues increasing even after garbage collection.
Consider an application that processes background jobs. Each job creates objects containing request information, processing results, and metadata. If these objects are retained after processing finishes, heap usage may gradually increase. Some common symptoms include:
- Increasing heap consumption during normal application operation.
- More frequent garbage collection cycles.
- Longer garbage collection pauses.
- Increasing response times.
- Application failures caused by
java.lang.OutOfMemoryError: Java heap space. - Memory usage that does not return to a relatively stable level after garbage collection.
We can begin by locating the running JVM process:
jcmd -l
Example output:
12540 com.jcg.example.JobProcessor
The number 12540 is the process identifier (PID). We can now inspect its heap information:
jcmd 12540 GC.heap_info
This provides information about the current heap configuration and usage. We can also monitor garbage collection statistics using jstat:
jstat -gcutil 12540 1000
The final argument specifies the monitoring interval in milliseconds. In this example, the command collects statistics every second. Pay attention to the percentage of used heap memory and the frequency of garbage collection activity. If the application continues accumulating memory after garbage collection, further investigation is necessary.
4.2 Determine Whether the Problem is in the Heap or Native Memory
Once we have established that memory consumption is increasing, the next step is to determine which memory area is responsible. This distinction prevents us from investigating the wrong part of the JVM. For example, increasing Java heap consumption may indicate that application objects are being retained. On the other hand, stable heap usage combined with increasing process memory may indicate a native memory problem.
We can investigate heap memory using:
jcmd 12540 GC.heap_info
For native memory, assuming Native Memory Tracking was enabled when the JVM started, execute:
jcmd 12540 VM.native_memory summary
We can also inspect the process’s resident memory using operating system tools. On Linux:
ps -p 12540 -o pid,rss,vsz,comm
The RSS column shows the resident memory currently used by the process, while VSZ represents its virtual memory size.
The following observations can help narrow down the problem:
| Observation | Possible explanation |
|---|---|
| Heap usage continuously increases | Objects may be retained in application collections or caches. |
| Heap usage increases and then stabilises | Normal allocation and garbage collection behaviour may be occurring. |
| Heap remains stable but process memory increases | Investigate native memory, thread stacks, direct buffers and native libraries. |
| Thread count increases continuously | Excessive thread creation may be consuming native memory. |
| Direct buffer usage increases | Investigate direct buffer allocation and retention. |
If the problem is in the Java heap, we can proceed by generating a heap dump. If native memory is responsible, we should investigate the relevant JVM subsystem, direct memory allocations, thread creation, or native libraries instead.
4.3 Capture a Heap Dump for Detailed Analysis
A heap dump is a snapshot of the objects currently present in the Java heap. It contains information about object instances, their fields, and the references connecting them. Heap dumps are valuable because they allow us to investigate what is occupying memory and, more importantly, what is preventing objects from being garbage collected.
We can generate a heap dump using jcmd:
jcmd 12540 GC.heap_dump heapdump.hprof
This command creates a file named heapdump.hprof in the current working directory of the command. The resulting file can be opened in Eclipse Memory Analyzer. Heap dumps can be large, especially when analysing applications with several gigabytes of heap memory. They may also contain sensitive application information, including user data, credentials, and request contents. Store them securely and avoid sharing them without appropriate protection.
4.4 Analyse the Heap Dump and Identify Retained Objects
After generating the heap dump, open Eclipse Memory Analyzer and load the .hprof file. MAT will analyse the heap and provide several reports that help identify potential memory leaks. Start with the Leak Suspects Report. This report identifies objects and object structures that may be responsible for excessive memory consumption.
Next, inspect the Dominator Tree. The Dominator Tree is useful because it shows which objects retain other objects in memory. An object dominates another object when every path from a garbage collection root to the dominated object passes through the dominating object.
For example, a static collection may retain thousands of job objects. Each job object may then retain several other objects, such as request data, processing results, and metadata. Although the individual job objects might not appear particularly large, the collection could indirectly retain a substantial amount of heap memory.
Select a suspicious object and inspect its retained heap. The retained heap indicates how much memory would become eligible for reclamation if the selected object were no longer reachable, taking its dominated objects into account.
Finally, use the Path to GC Roots feature to understand why the object remains in memory. This is often where the actual cause of the problem becomes apparent. You may discover that a static field, application cache, ThreadLocal variable, or another long-lived object is maintaining a reference to data that should have been released.
5. Example: Finding and Fixing a Heap Memory Leak in a Java Application
We will now apply the diagnostic workflow to a small Java application that simulates a background job processing system. The application will create job records containing information about completed jobs. However, it will retain every processed job in a static collection.
This is an intentional memory leak. It gives us a practical example of how objects can remain in memory even after the application has finished using them. Our objective is to run the application, inspect its memory usage using jcmd, generate a heap dump, and analyse the dump using Eclipse Memory Analyzer. We will then correct the implementation and compare the results.
5.1 Create the Example Application
Create a Java project with the following structure:
java-memory-leak/
âââ src/
âââ main/
âââ java/
âââ com/
âââ example/
âââ Job.java
âââ JobProcessor.java
âââ Main.java
The application will contain three classes. The Job class represents a background job. Each job contains an identifier, a description, and a payload containing additional processing information.
The JobProcessor class processes jobs and maintains a collection of completed jobs. The Main class continuously submits jobs to simulate an application that processes background tasks.
public class Job {
private final String id;
private final String description;
private final byte[] payload;
public Job(String description) {
this.id = UUID.randomUUID().toString();
this.description = description;
// Simulate job data occupying approximately 100 KB.
this.payload = new byte[100 * 1024];
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public byte[] getPayload() {
return payload;
}
}
The Job class creates a byte array of approximately 100 KB whenever a new job is instantiated. In a real application, this payload could represent request data, processing results, or other information required while a job is executing.
public class JobProcessor {
private static final List<Job> completedJobs =
new ArrayList<>();
public void process(Job job) {
// Simulate job processing.
System.out.println("Processing job: " + job.getId());
// Simulate completed job processing.
completedJobs.add(job);
}
}
The problem is in the completedJobs collection. It is declared as a static field, meaning that it remains associated with the JobProcessor class for the lifetime of the class loader.
Every processed job is added to this collection, and no code removes completed jobs. Consequently, the application retains every Job instance, including its payload, even though processing has finished.
public class Main {
public static void main(String[] args)
throws InterruptedException {
JobProcessor processor = new JobProcessor();
long counter = 0;
while (true) {
Job job = new Job("Background Job " + counter);
processor.process(job);
counter++;
if (counter % 100 == 0) {
System.out.println(
"Total processed jobs: " + counter
);
}
Thread.sleep(10);
}
}
}
The main method continuously creates and processes jobs. Each job adds approximately 100 KB of payload data to the completed jobs collection. The application pauses for 10 milliseconds between jobs to make the memory growth easier to observe.
Although the local job variable is overwritten during the next iteration, the objects remain reachable through the static completedJobs collection. This is the source of the memory leak.
5.2 Compile and Run the Application
Compile the application from the project directory:
javac -d out src/main/java/com/jcg/example/*.java
Run it with a limited heap size:
java -Xms64m -Xmx256m \
-cp out \
com.jcg.example.Main
The JVM options specify the initial and maximum heap sizes.
-Xms64msets the initial heap size to 64 MB.-Xmx256mlimits the maximum Java heap size to 256 MB.
Limiting the heap makes it easier to reproduce the problem without allowing the application to consume an unnecessarily large amount of memory. As the application runs, it continuously creates new jobs and retains them in memory.
Eventually, the application will experience an error similar to:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
This happens because the completed jobs collection continues growing until the JVM cannot allocate additional objects.
5.3 Locate the Running JVM Process
Instead of waiting for the application to fail, we can inspect its memory usage while it is running. Open another terminal window and execute:
jcmd -l
The output should contain the running application:
18240 com.jcg.example.Main
The process identifier will differ on your machine. We will use 18240 in the following examples.
5.4 Inspect the Heap with jcmd
We can now inspect the Java heap:
jcmd 18240 GC.heap_info
This command displays information about the current heap configuration and memory usage. The exact output depends on the JDK version and garbage collector being used, but it will contain information about the heap’s current capacity and occupied memory.
Next, we can inspect the objects currently present in the heap using a class histogram:
jcmd 18240 GC.class_histogram
The histogram displays the number of instances of each class, along with their shallow heap consumption. A simplified example might look like this:
num #instances #bytes Class ---------------------------------------------- 1 8500 870400000 [B 2 8500 680000 com.example.Job 3 8500 204000 java.lang.String 4 150 12000 java.util.ArrayList
The [B entry represents byte arrays. The large number of byte arrays indicates that the application is retaining substantial amounts of payload data. The histogram provides a useful starting point, but it does not tell us why these arrays remain in memory. To understand that, we need to examine the object references using a heap dump.
5.5 Generate a Heap Dump
We can now generate a heap dump while the application is still running. Execute:
jcmd 18240 GC.heap_dump heapdump.hprof
The JVM will create a heap dump named heapdump.hprof. This file contains a snapshot of the Java heap at the time the command executes. Depending on the JVM configuration and heap size, generating a heap dump may temporarily affect application performance. For production systems, consider the operational impact and available disk space before capturing one.
5.6 Open the Heap Dump in Eclipse Memory Analyzer
Start Eclipse Memory Analyzer and open the generated heapdump.hprof file. MAT will parse the dump and display an overview of the heap, including the number of objects, classes, and memory consumed.
From the available reports, select Leak Suspects Report. The report may identify the completedJobs collection as a potential source of excessive memory retention. However, we should not rely exclusively on the automatic leak report. We also need to inspect the actual reference structure.
Open the Dominator Tree and locate the JobProcessor class and its static completedJobs field. The collection retains thousands of Job objects. Each job, in turn, retains its associated byte array.
The relationship can be represented conceptually as:
JobProcessor
|
| static reference
v
completedJobs (ArrayList)
|
+---- Job
| |
| +---- byte[] payload
|
+---- Job
| |
| +---- byte[] payload
|
+---- Job
|
+---- byte[] payload
This is the reference chain responsible for retaining the memory. Select one of the Job objects and use the Path to GC Roots feature to investigate why it remains reachable. The analysis should reveal that the Job instance is reachable through the static completedJobs collection. This confirms our suspicion: the application is retaining completed jobs indefinitely.
5.7 Understand the Root Cause
We have now identified the source of the memory leak. The problem is not caused by the garbage collector failing to perform its job. Instead, the application has created a reference structure that prevents the garbage collector from identifying the completed jobs as unreachable.
The completedJobs collection is a static field. As long as the class remains loaded, the collection remains reachable. Every job added to that collection also remains reachable, along with its payload. The application therefore continues consuming additional heap memory as more jobs are processed.
This is a problem in long-running Java applications. We may introduce collections for caching, tracking, or processing objects but forget to define when those objects should be removed. The solution is to change the application’s object lifecycle so that completed jobs are not retained unnecessarily.
5.8 Fix the Memory Leak
In this example, we do not need to keep completed jobs after they have been processed. We can remove the static collection entirely and process each job without retaining a reference to it.
Replace the original JobProcessor.java with the following implementation:
public class JobProcessor {
public void process(Job job) {
// Simulate job processing.
System.out.println("Processing job: " + job.getId());
// Process the job and release references
// when processing is complete.
}
}
The updated implementation no longer stores completed jobs in a static collection. Once the process() method finishes and no other references exist, the job object becomes eligible for garbage collection.
The Main.java class does not need to change:
public class Main {
public static void main(String[] args)
throws InterruptedException {
JobProcessor processor = new JobProcessor();
long counter = 0;
while (true) {
Job job = new Job("Background Job " + counter);
processor.process(job);
counter++;
if (counter % 100 == 0) {
System.out.println(
"Total processed jobs: " + counter
);
}
Thread.sleep(10);
}
}
}
Now, the application can continue processing jobs without accumulating references to previously completed jobs. It is important to understand that making an object eligible for garbage collection does not mean that the JVM immediately reclaims its memory. Garbage collection occurs according to the JVM’s allocation and collection policies. The important change is that the application no longer prevents those objects from being collected.
5.9 Compare Memory Usage Before and After the Fix
After modifying the code, compile and run the application again:
javac -d out src/main/java/com/jcg/example/*.java
Start the application:
java -Xms64m -Xmx256m \
-cp out \
com.jcg.example.Main
Locate the new process:
jcmd -l
Then inspect its heap:
jcmd <pid> GC.heap_info
We can also inspect the class histogram again:
jcmd <pid> GC.class_histogram
Unlike the original implementation, the updated application should no longer accumulate thousands of retained Job instances. The number of live Job objects should remain relatively small, although the exact number depends on garbage collection timing and the JVM’s allocation behaviour.
For a more reliable comparison, generate another heap dump:
jcmd <pid> GC.heap_dump heapdump-fixed.hprof
Open both the original and updated heap dumps in MAT and compare their object counts, retained heap sizes, and dominator trees. The original dump should show the completedJobs collection retaining a growing number of Job objects and their associated byte arrays. The updated dump should no longer contain that growing collection of completed jobs.
6. Common Causes of Memory Leaks in Java Applications
The example above demonstrates one of the simplest forms of a memory leak, but real applications can retain objects through several different mechanisms. Understanding these common causes can make debugging considerably easier.
6.1 Unbounded Collections
Collections such as ArrayList, HashMap, and HashSet can become sources of memory leaks when objects are continuously added without an appropriate removal strategy. For example:
private static final Map<String, Object> CACHE =
new HashMap<>();
If the application adds every request result to this map and never removes old entries, the collection can grow indefinitely. A cache should have an appropriate eviction policy, maximum size, or expiration strategy.
6.2 Static References
Static fields remain associated with their class for as long as the class remains loaded. This makes them suitable for application-wide configuration and shared resources, but they can also accidentally retain large object graphs.
For example, a static collection containing user sessions or request objects may prevent those objects from being garbage collected even after they are no longer needed.
6.3 Listeners and Event Handlers
Applications frequently register listeners to receive notifications from other components. A problem occurs when listeners are registered but never removed. For example:
eventSource.addListener(listener);
If the listener is no longer required, the application should unregister it:
eventSource.removeListener(listener);
Otherwise, the event source may retain a reference to the listener and everything reachable through it.
6.4 ThreadLocal Variables
ThreadLocal allows each thread to maintain its own copy of a variable. This is useful in applications that need thread-specific state. However, problems can occur when application servers or thread pools reuse threads and ThreadLocal values are not removed after processing a request.
For example:
private static final ThreadLocal<byte[]> DATA =
new ThreadLocal<>();
public void processRequest() {
DATA.set(new byte[1024 * 1024]);
// Perform request processing.
DATA.remove();
}
Calling remove() after processing prevents the thread from unnecessarily retaining the value.
6.5 Incorrect Resource and Object Lifecycle Management
Some memory problems are related to resources such as direct buffers, native allocations, and objects managed by external libraries. We should understand how these resources are allocated and released.
For example, file streams and database connections should be closed appropriately, preferably using try-with-resources. Although failing to close a file stream is not automatically a Java heap memory leak, unmanaged resources can contribute to resource exhaustion and other application stability problems.
7. Best Practices for Preventing Java Memory Leaks
Preventing memory leaks is generally easier than diagnosing them after an application has been deployed. Developers should consider object ownership and lifecycle management when designing Java applications, especially services that run continuously.
The following practices help reduce the risk of memory leaks.
Use bounded collections and caches. Avoid allowing collections to grow indefinitely. Define maximum sizes, expiration policies, and eviction strategies where appropriate.
Remove unnecessary references. When objects are no longer required, remove them from collections, maps, listener registries, and other long-lived structures.
Manage ThreadLocal values carefully. Always consider removing thread-specific values after request processing, particularly when working with thread pools.
Monitor garbage collection behaviour. Regularly monitor heap usage, allocation rates, and garbage collection activity. Unexpected increases can reveal memory problems before they become critical.
Use profiling tools during development. Tools such as JFR, JMC, VisualVM, and Eclipse MAT can help identify excessive object allocation and retention.
Test long-running application behaviour. Memory problems may not appear during short tests. Run applications under realistic workloads for extended periods and monitor whether heap usage stabilises.
Understand object ownership. Every long-lived object should have a clear reason for retaining references to other objects. This is especially important in caches, background processing systems, event-driven applications, and application servers.
8. Conclusion
Diagnosing a Java heap memory leak requires understanding how objects are allocated, referenced, and retained by an application. Although garbage collection automatically reclaims unreachable objects, it cannot remove objects that remain reachable through unnecessary references. In this article, we examined how to identify increasing heap consumption, distinguish heap problems from native memory issues, and use jcmd to inspect a running JVM. We also generated a heap dump and analysed it using Eclipse Memory Analyzer to identify the static collection responsible for retaining completed job objects.
The key takeaway is that fixing a Java memory leak requires identifying and removing the unnecessary references that prevent objects from becoming eligible for garbage collection. Monitoring memory usage, understanding object lifecycles, and using diagnostic tools such as jcmd and MAT make it possible to investigate these problems systematically and build more reliable long-running Java applications.

