Debugging Java Heap Space Errors

Memory leaks are a pain. If you’re like me, the first thing you did when your application threw a “Java Heap Space Error” exception, was to increase your java virtual machine’s heap space parameters. There are a number of reasons why you should probably avoid doing this (worth googling), but nonetheless I tried this and it didn’t work (just prolonged the time to failure and slowed my application down).  After much googling, I learned that heap space errors should really not occur unless you’ve screwed up somewhere in your code. In my case, I had just finished creating a testing application which used a colleagues terminology service (I program health IT apps), and because my tester ran for a few days in duration, any small memory leak became a big one. To diagnose the cause of the memory leak(s) I spent a lot of time researching java memory analyzing tools (most were really expensive), but it was the FREE Java Visual VM tool that finally helped me solve my problem. The Java Visual VM application (i.e. the jvisualvm.exe executable stored in your java sdk’s installations bin folder) allows you to track applications resource utilization, and also take memory snapshots (aka. memory dumps) while your application is running. You can then drill down into your application and figure out which objects are taking up the most space. Usually, the objects/classes that are taking up the most space are the cause of your memory leak. My issue ended up being due to my colleagues code not closing db connections and prepared statement (a common cause of memory leaks in Java).  So after fixing my colleague’s code, my tester was running faster, and most importantly, it didn’t crash.


This entry was posted in Java, Programming, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *