Memory Leaks in Java

Original Posting Date: 11/26/2008.

There is an excellent blog that describes classloaders and memory leaks in Java: Frank Kievet Blog. The next entry in the blog shows a new tool from Java 1.6 that can be used to isolate memory leaks.

In summary

  1. If a class from outside the web app makes a hard link to an object in your web app, then you have a memory leak.
  2. There are many packages that cause such leaks.
Two of the packages that Hibernate uses cause such leaks.
  1. org.hibernate.util.XMLHelper (and a package that references this: org.hibernate.cfg.Configuration)
  2. net.sf.cglib

The first memory leak can be removed by modifying XMLHelper. There is a static variable that is not used anywhere, except in Configuration. By removing the variable from XMLHelper and removing the reference to it (replace with null) in Configuration, the leak goes away.

The second memory leak is more entwined in cglib. The leak can be removed by having cglib loaded by a different classloader than the one for the web app. The solution is to move the cglib jar and the asm jar to the shared lib directory of Tomcat.

I have recompiled hibernate and created zip files for the jar files that still belong in the web app and the two that belong in the shared lib directory of Tomcat. If you are using a system and do not have access to the shared lib folder (or common lib folder), then place these jars in the web app with the understanding that you will run out of memory eventually.