Common Causes for Memory Leaks

You’ll always have to deal with memory issues, no matter the programming language. Even with the Java programming language, if the right precautions are not taken, you will have some sort of memory leaks, memory issue, out of memory exception, or heap size problem. I’ve seen two common types of memory issues in every application I’ve worked on.

A common source of memory leaks is global static singleton god object that collects or manages a lot of data, maybe a system cache, object lookup table, service locator, etc. This type of singleton pattern will require other objects to register with it, add themselves to the global pool of objects, but if they are not properly removed, unregistered, when they are no longer needed you will see your memory usage increase over time. I’ve seen this issue when using the callback or listener pattern and the listener object itself holds a lot of other data. This sort of problem is usually relatively easy to identify with a profiler, it will usually be one of the largest objects in your system.

The other, more difficult memory leak to identify, is when you have hundreds of thousands of objects each taking up a reasonable amount of memory. In this case, a single object instance will not take a lot of memory but collectedly the hundreds of thousands of objects can eat up a lot of memory. Here are a few things you can think about when dealing with a small class that spawns thousand of objects…

If you have int types, see if you can change them to short or byte types. Try subclassing if you have any number of properties that most often than not set or are null. Think about lazy loading arrays, lists, and other objects references. If there are many object instances of this class, and any portion of these instances are logically equivalent, think of using the flyweight pattern.


Leave a Reply