Archive

Archive for the ‘Debug’ Category

Memory leaks in Java

December 19, 2011 Leave a comment

Programming in Java relieves from a certain burden of self managing memory allocation/de-allocation, however, that doesn’t mean completely overlooking this aspect at the risk of creating memory ogres instead of programs.
The JVM will try to allocate memory up to the max memory heap you specify, this pool of memory is reclaimed by the Garbage Collector once your instances are dereferenced. Obviously if you keep on creating objects you’ll fill up your memory and the JVM will throw an exception!
java.lang.OutOfMemoryError: Java heap space
Such errors are quite easy to spot with a debugger; The real fun starts when you’ve got a memory leak in your program (or a bug in a 3rd party library you use) which will only appear under some heavy load and long runs. Finding the error might be tedious because that involves trying to reproduce it at first, analyzing memory maps, sort what is normal and what’s not; fortunately there is a plenty of tools out there to help.
Monitor your application with Jconsole: This monitoring utility could be very useful to spot patterns of memory growth in your application. Fist pass a couple of options to your JVM to activate JMX remote monitoring, for example here I open the 7777 port and disable all security (you might want to activate it .. though :)
-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=7777 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
Then from a remote machine launch Jconsole client using jconsole host:port
Produce memory heaps by passing the following parameter to the JVM:
-XX:+HeapDumpOnOutOfMemoryError
Use Jmap to create a dump on the fly i.e: while the application is running.
Look at the content of the Heap: In order to examine the heap files you produce you need to read them with a specific tool. Jhat is a small utility that reads the heap file and launces a web browser from which you can browse its content, you’ll find: current objects, their references, size, hiarchy and so on. A histogram summary might be the first thing you want to look at since it gives the list of classes ordered by number of instances and memory usage.
So far all those tools are shipped with latest versions of JVM, now if you want a more detailed insight or automatic leak suspect report, there is some free tools like: Eclipse Memory Analyzer tool and Netbeans profiler.
All the tools listed here were usually enough for me to find memory leaks. Although a bit tedious, my strategy is to create heap dump files on the fly at different moments and then examine the differential.

Categories: Debug, Java, OutOfMemoryError
Follow

Get every new post delivered to your Inbox.