Tomcat has long been blamed for causing memory leaks in the permanent generation (PermGen) that lead to OutOfMemoryErrors when re-loading web applications. I was discussing this at the eJUG days conference last year when I made an off-the-cuff remark that these errors were nearly always application bugs rather then Tomcat bugs. This generated a fair amount of debate that ended up with me doing some impromtu debugging of a couple of web applications provided by the audience.
The result of the debugging was that we found a number of root causes for the memory leaks that were fairly evenly split between application code, library code and JVM code. As I was coding some fixes for these issues, I realised that Tomcat could prevent a number of these memory leaks and detect even more. Not only that, in a number of cases it looked to be possible for Tomcat to actually fix the memory leak when it detected it. This lead, ultimately, to the new memory leak prevention and detection in Tomcat 6.
There are two parts to the new memory leak features. The first part handles memory leak prevention and is implemented as a life-cycle listener, the JreMemoryLeakPreventionListener. This listener prevents memory leaks by calling various parts of the Java API that are known to retain a reference to the current context class loader. If a web application is the first code to call one of these standard Java APIs, the web application class loader will be pinned in memory which will cause a memory leak. By making sure that Tomcat code makes the calls first, the memory leaks are prevented. If you want to know the gritty details of what this listener actually does, the source code is pretty well commented.
The second part of the new features handles detection. This code executes when a web application is stopped, un-deployed or reloaded. It checks, via a combination of standard API calls and some reflection tricks, for known causes of memory leaks and - where it can - fixes them. These checks are implemented in the WebappClassLoader. A nice explanation of what these checks do has been written by Sylvain Laurent on the Tomcat Wiki. As always with Tomcat, if you want the details you can look at the source code. Start with the clearReferences() method.
The memory leak detection and prevention code is still a work in progress. More detections and preventions will be added as they are identified. If you are aware of a category of memory leaks that aren't currently detected or protected against, I encourage you to bring this to the attention of the Tomcat developers via the Tomcat developer mailing list.