title: Is there a way to avoid undeployment memory leaks in Tomcat?
body: <p>This question is for anyone who's ever tested the "Find leaks" button in the Tomcat manager and got some results like this:</p>
  
  <blockquote>
    <p>The following web applications were stopped (reloaded, undeployed), but their classes from previous runs are still loaded in memory, thus causing a memory leak (use a profiler to confirm): <br>
    /leaky-app-name</p>
  </blockquote>
  
  <p>I'm assuming this has something to do with that "Perm Gen space" error you often get with frequent redeployments.</p>
  
  <p>So what I'm seeing in jconsole when I deploy is that my loaded classes goes from about 2k to 5k. Then you would think an undeployment should drop them back down to 2k but they remain at 5k.</p>
  
  <p>I've also tried using the following JVM options: </p>
  
  <p><code>-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled</code></p>
  
  <p>I did see VERY minor dips in the amount of Perm Gen space used but not what I expected and the loaded class counts did not drop.</p>
  
  <p>So is there a way to configure Tomcat or design your app to unload better on an undeployment? Or are we stuck with restarting the server after some major debugging sessions?</p>
  
  <p>Tomcat version output:</p>
  
  <blockquote>
    <p>Server version: Apache Tomcat/6.0.29 <br>
    Server built:   July 19 2010 1458 <br>
    Server number:  6.0.0.29 <br>
    OS Name:        Windows 7 <br>
    OS Version:     6.1 <br>
    Architecture:   x86 <br>
    JVM Version:    1.6.0_18-b07 <br>
    JVM Vendor:     Sun Microsystems Inc. <br></p>
  </blockquote>
  
  <p><strong>Update:</strong></p>
  
  <p>Thanks to celias' answer I decided to do a little more digging and I think I determined the culprit to be in my application thanks to CXF, Spring and JAXB.</p>
  
  <p>After I learned how to profile a Java application, I pointed the profiler at Tomcat and took some heap dumps and snapshots to see what the objects and classes looked like in memory. I discovered that some of the enumerations from my XML schema used in my CXF/JAXB (wsdl2java) generated classes were lingering after an undeployment. According to my heap dump it looks like the objects were tied to a Map. Disclaimer: I admit I'm still a little green with profiling and tracing an object's call tree can be challenging in Java.</p>
  
  <p>Also I should mention that I didn't even invoke the service, just deployed then undeployed it. The objects themselves appeared to be loaded via reflection initiated from Spring on deployment. I believe I followed the convention for setting up a CXF service in Spring. So I'm not 100% sure if this is Spring/CXF, JAXB, or reflection's fault.</p>
  
  <p>As a side note: the application in question is a web service using Spring/CXF and the XML happens to be a rather complex schema (an extension of <a href="http://www.niem.gov/implementationguide.php">NIEM</a>).</p>