Sun.net.www.http.HttpClient memory leak in Tomcat 6

I am using Tomcat 6.0.18 . After undeployemnt my application, HttpClient seems to hold a link to WebappClassLoader, which causes a memory leak.

After some investigation, I found a solution in Tomcat 7.0.6 , JreMemoryLeakPreventionListener with keepAliveProtection . But this approach does not work with Tomcats 6 (I configured JreMemoryLeakPreventionListener to add support for this attribute).

Does anyone have a solution how to fix this leak in Tomcat 6? Thanx!

+6
source share
1 answer

I found a solution for memory leak.

You must run the ServletContextListener , as shown below:

package org.example; public class MyServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent sce) { tomcatLeakPreventionForHttpClient(); } private void tomcatLeakPreventionForHttpClient() { try { final Field kac = HttpClient.class.getDeclaredField("kac"); kac.setAccessible(true); final Field keepAliveTimer = KeepAliveCache.class.getDeclaredField("keepAliveTimer"); keepAliveTimer.setAccessible(true); final Thread t = (Thread) keepAliveTimer.get(kac.get(null)); if(t.getContextClassLoader() == Thread.currentThread().getContextClassLoader()) { t.setContextClassLoader(ClassLoader.getSystemClassLoader()); } } catch(final Exception e) { } } public void contextInitialized(ServletContextEvent event) { } } 

and, of course, register the listener in web.xml:

  <listener> <listener-class>org.example.MyServletContextListener</listener-class> </listener> 
+8
source

Source: https://habr.com/ru/post/890659/


All Articles