Tuesday, August 21, 2007

Java: PermGen OutOfMemory

This blog is in relation to Java PermGen OutOfMemory issue as described in Frank Kieviet's blog entries:

    Classloader leaks and How to fix Classloader leaks? 

To summarize, a new instance of custom Classloader is created by Application Server whenever a new application (.ear, .jar, .war) is deployed to the server, and this Classloader is used to load all the classes and resources contained in this application.  Benefit in this approach is that, this way applications are self-contained and isolated from each other, and there are no conflicts between different applications.  When an application is undeployed from server, its associated Classloader is also unloaded, and it is subject to garbage-collection by JVM.

As described in Frank's blog, there are situations in which Classloaders cannot be garbage-collected because of dangling references to them thru most unexpected places, and this will cause memory-leak in the PermGen space (a special section of heap).  To find the cause of this problem, I used JDK 6.0's jmap and jhat utility to generate memory dump and analyze memory dump, respectively.

Orphaned Classloader

jhat utility can be easily extended to include your own query on the heap snapshot, you need to download and modify the jhat source code though.  I added a new query to find all the Orphaned Classloaders in memory and display all the reference links to these Orphaned Classloaders.  By orphaned, I mean these classloader instances that have no strong-reference chains to them from the root set, except by these strong-references chains from rootset that goes through instance of Class loaded by the Classloader.  To illustrate this, see the diagram below (solid line = strong-reference, dash-line = weak-reference) :

The yellow Classloader instance is orphaned, because the only strong-reference chain to it from root set is the chain that goes through B.class, and B.class is loaded by this Classloader (all the red lines).  All other references that do not go through classes loaded by this Classloader are weak-references.  This scenario is a possible suspect of Classloader leak, because most likely Orphaned Classloaders are not intended result of programmer, there are exceptions though.  By using this query, we can easily find all the possible suspects, and then goes through each one to determine if they are real memory leak or not.

blogs.sun.com

3 Comments:

PeterReilly said...

I would be interested in this query - can
you post a patch for please?

Anonymous said...

I have used JConsole to expose a major memory leak issue in Tomcat

http://blogs.boxysystems.com/2007/4/11/tomcat-v5-0-28-memory-leak-exposed

Anonymous said...

It would be great if you can share the code of your customized query.