How to Fix Memory Leaks in Java
What Are Memory Leaks?
Let’s start by describing how memory leaks happen in Java. Java implements automatic garbage collection (GC), and once you stop using an object you can depend on the garbage collector to collect it. While additional details of the collection process are important when tuning GC performance, for the sole purpose of fixing a memory leak we can safely ignore them.Is My Program Leaking Memory?
Not every OutOfMemoryError alert indicates that a program is suffering from a memory leak. Some programs simply need more memory to run. In other words, some OutOfMemoryError alerts are caused by the load, not by the passage of time, and as a result they indicate the need for more memory in a program rather than a memory leak.To distinguish between a memory leak and an application that simply needs more memory, we need to look at the “peak load” concept. When program has just started no users have yet used it, and as a result it typically needs much less memory then when thousands of users are interacting with it. Thus, measuring memory usage immediately after a program starts is not the best way to gauge how much memory it needs! To measure how much memory an application needs, memory size measurements should be taken at the time of peak load—when it is most heavily used.
How To Find Leaked Objects in a Fast Memory Leak
Somewhat surprisingly, it is much easier to debug large memory leaks than small memory leaks. The reason is that memory leaks present a sort of “needle in the haystack” type problem—you need to find the leaked objects amongst all the other objects in the program.Tools for Dealing with Heap Dumps
Strictly speaking, you don’t need any tools that are not already part of the JDK. JDK ships with a tool called that, which you can use to inspect the heap dump. The process of fixing memory leaks is the same with all tools, and it’s our opinion that no single tool is “light years” ahead of the others when it comes to fixing memory leaks.Although that will get the job done, better tools often provide a few extra helpful features:
- Present a better summary of heap statistics.
- Sort objects by retained heap. In other words, some tools can tell you the memory usage of an object and all other objects that are referenced by it, as well as list the objects referenced by other objects. This makes it much faster to diagnose the cause of a memory leak.
- Function on machines that have less memory then the size of the heap dump. For example, they’ll allow you to analyze a 16GB heap dump from your server on a machine with only 1GB of physical memory.