How classloaders leak can lead to permgen memory issues

A class belongs to it’s ClassLoader, to reload the class you need to create a new ClassLoader and load the class with a new ClassLoader.

Each web application in Tomcat or any webserver has its own class loader; this allows different versions of the same class (with the same name) to be used in different web applications without conflict. A web application also gets a new class loader when it is reloaded. Classes are removed from PermGen when the class loader is collected by the garbage collector.

A classloader will be removed by the garbage collector only if nothing else refers to it. All classes hold a reference to their classloader and all objects hold references to their classes. As a result, if an application gets unloaded but one of its objects is still being held (e.g., by a cache or a thread-local variable), the underlying classloader cannot not be removed by the garbage collector!

For example a web application creates an object of a class loaded by the web application class loader and then places this object in a registry that has been loaded by a different class loader. This is fine, as long as the object is removed from the registry when the web application stops. If the object is not removed, the registry retains a reference to the object, the object retains a reference to the class and the class retains a reference to the class loader. This pins the class loader in memory. This chain of references prevents the class loader from being garbage collected which in turn means that the PermGen used to store classes loaded by this class loader cannot be freed.

Uday Ogra

Connect with me at and lets have some healthy discussion :)

You may also like...

Leave a Reply

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