Author: markt Date: Fri Mar 9 19:08:49 2012 New Revision: 1298983 URL: http://svn.apache.org/viewvc?rev=1298983&view=rev Log: Fix https://issues.apache.org/bugzilla/show_bug.cgi?id=52850 Enable the memoey leak protection code to play nicely with IBM JVMs as well as Oracle JVMs. Extend test case coverage of memory leak protection. Patch provided by Rohit Kelapure.
Added: tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderThreadLocalMemoryLeak.java Modified: tomcat/trunk/java/org/apache/catalina/loader/WebappClassLoader.java Modified: tomcat/trunk/java/org/apache/catalina/loader/WebappClassLoader.java URL: http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/loader/WebappClassLoader.java?rev=1298983&r1=1298982&r2=1298983&view=diff ============================================================================== --- tomcat/trunk/java/org/apache/catalina/loader/WebappClassLoader.java (original) +++ tomcat/trunk/java/org/apache/catalina/loader/WebappClassLoader.java Fri Mar 9 19:08:49 2012 @@ -27,6 +27,7 @@ import java.io.InputStream; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; @@ -2244,8 +2245,7 @@ public class WebappClassLoader } // TimerThread can be stopped safely so treat separately - if (thread.getClass().getName().equals( - "java.util.TimerThread") && + if (thread.getClass().getName().startsWith("java.util.Timer") && clearReferencesStopTimerThreads) { clearReferencesStopTimerThread(thread); continue; @@ -2268,20 +2268,28 @@ public class WebappClassLoader // If the thread has been started via an executor, try // shutting down the executor try { - Field targetField = - thread.getClass().getDeclaredField("target"); - targetField.setAccessible(true); - Object target = targetField.get(thread); - - if (target != null && - target.getClass().getCanonicalName().equals( - "java.util.concurrent.ThreadPoolExecutor.Worker")) { - Field executorField = - target.getClass().getDeclaredField("this$0"); - executorField.setAccessible(true); - Object executor = executorField.get(target); - if (executor instanceof ThreadPoolExecutor) { - ((ThreadPoolExecutor) executor).shutdownNow(); + + Field targetField = null; + try { + targetField = thread.getClass().getDeclaredField("target"); + }catch (NoSuchFieldException nfe){ + targetField = thread.getClass().getDeclaredField("runnable"); + } + if (null != targetField){ + targetField.setAccessible(true); + Object target = targetField.get(thread); + + if (target != null && + target.getClass().getCanonicalName() != null + && target.getClass().getCanonicalName().equals( + "java.util.concurrent.ThreadPoolExecutor.Worker")) { + Field executorField = + target.getClass().getDeclaredField("this$0"); + executorField.setAccessible(true); + Object executor = executorField.get(target); + if (executor instanceof ThreadPoolExecutor) { + ((ThreadPoolExecutor) executor).shutdownNow(); + } } } } catch (SecurityException e) { @@ -2350,21 +2358,33 @@ public class WebappClassLoader // - queue.clear() try { - Field newTasksMayBeScheduledField = - thread.getClass().getDeclaredField("newTasksMayBeScheduled"); - newTasksMayBeScheduledField.setAccessible(true); - Field queueField = thread.getClass().getDeclaredField("queue"); - queueField.setAccessible(true); - - Object queue = queueField.get(thread); - - Method clearMethod = queue.getClass().getDeclaredMethod("clear"); - clearMethod.setAccessible(true); - - synchronized(queue) { - newTasksMayBeScheduledField.setBoolean(thread, false); - clearMethod.invoke(queue); - queue.notify(); // In case queue was already empty. + + try { + Field newTasksMayBeScheduledField = + thread.getClass().getDeclaredField("newTasksMayBeScheduled"); + newTasksMayBeScheduledField.setAccessible(true); + Field queueField = thread.getClass().getDeclaredField("queue"); + queueField.setAccessible(true); + + Object queue = queueField.get(thread); + + Method clearMethod = queue.getClass().getDeclaredMethod("clear"); + clearMethod.setAccessible(true); + + synchronized(queue) { + newTasksMayBeScheduledField.setBoolean(thread, false); + clearMethod.invoke(queue); + queue.notify(); // In case queue was already empty. + } + + }catch (NoSuchFieldException nfe){ + Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); + if (null != cancelMethod){ + synchronized(thread) { + cancelMethod.setAccessible(true); + cancelMethod.invoke(thread); + } + } } log.error(sm.getString("webappClassLoader.warnTimerThread", @@ -2394,21 +2414,29 @@ public class WebappClassLoader inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible - Class<?> tlmClass = - Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); + Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); + Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); + expungeStaleEntriesMethod.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { + // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); - checkThreadLocalMapForLeaks(threadLocalMap, tableField); + if (null != threadLocalMap){ + expungeStaleEntriesMethod.invoke(threadLocalMap); + checkThreadLocalMapForLeaks(threadLocalMap, tableField); + } + // Clear the second map - threadLocalMap = - inheritableThreadLocalsField.get(threads[i]); - checkThreadLocalMapForLeaks(threadLocalMap, tableField); + threadLocalMap =inheritableThreadLocalsField.get(threads[i]); + if (null != threadLocalMap){ + expungeStaleEntriesMethod.invoke(threadLocalMap); + checkThreadLocalMapForLeaks(threadLocalMap, tableField); + } } } } catch (SecurityException e) { @@ -2426,6 +2454,12 @@ public class WebappClassLoader } catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", contextName), e); + } catch (InvocationTargetException e) { + log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", + contextName), e); + } catch (NoSuchMethodException e) { + log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", + contextName), e); } } @@ -2529,7 +2563,7 @@ public class WebappClassLoader ClassLoader cl = clazz.getClassLoader(); while (cl != null) { - if(cl == this) { + if (cl == this) { return true; } cl = cl.getParent(); Added: tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java URL: http://svn.apache.org/viewvc/tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java?rev=1298983&view=auto ============================================================================== --- tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java (added) +++ tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderExecutorMemoryLeak.java Fri Mar 9 19:08:49 2012 @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.catalina.loader; + +import java.io.IOException; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import junit.framework.Assert; + +import org.apache.catalina.Context; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.startup.Tomcat; +import org.apache.catalina.startup.TomcatBaseTest; +import org.junit.Test; + +public class TestWebappClassLoaderExecutorMemoryLeak extends TomcatBaseTest { + + @Test + public void testTimerThreadLeak() throws Exception { + Tomcat tomcat = getTomcatInstance(); + + // Must have a real docBase - just use temp + Context ctx = tomcat.addContext("", + System.getProperty("java.io.tmpdir")); + + if (ctx instanceof StandardContext) { + ((StandardContext) ctx).setClearReferencesStopThreads(true); + } + + Tomcat.addServlet(ctx, "taskServlet", new ExecutorServlet()); + ctx.addServletMapping("/", "taskServlet"); + + tomcat.start(); + + // This will trigger the timer & thread creation + getUrl("http://localhost:"; + getPort() + "/"); + + // Stop the context + ctx.stop(); + + // If the thread still exists, we have a thread/memory leak + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + // ignore + } + + Assert.assertTrue(ExecutorServlet.tpe.isShutdown()); + Assert.assertTrue(ExecutorServlet.tpe.isTerminated()); + } + + static class ExecutorServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + int nTasks = 5; + long n = 1000L; + int tpSize = 10; + + public static ThreadPoolExecutor tpe; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + resp.getWriter().println( + "The current thread served " + this + " servlet"); + tpe = new ThreadPoolExecutor(tpSize, tpSize, 50000L, + TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); + + Task[] tasks = new Task[nTasks]; + for (int i = 0; i < nTasks; i++) { + tasks[i] = new Task("Task " + i); + tpe.execute(tasks[i]); + } + resp.getWriter().println("Started " + nTasks + + " never ending tasks using the ThreadPoolExecutor"); + resp.getWriter().flush(); + } + + class Task implements Runnable { + + String _id; + + public Task(String id) { + this._id = id; + } + + @Override + public void run() { + try { + while (!Thread.currentThread().isInterrupted()) { + Thread.sleep(20000); + System.out.println(Thread.currentThread().getClass() + + " [" + Thread.currentThread().getName() + + "] executing " + this._id); + } + } catch (InterruptedException e) { + System.out.println(Thread.currentThread().getClass() + " [" + + Thread.currentThread().getName() + "] EXITING"); + } + } + } + } +} Added: tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderThreadLocalMemoryLeak.java URL: http://svn.apache.org/viewvc/tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderThreadLocalMemoryLeak.java?rev=1298983&view=auto ============================================================================== --- tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderThreadLocalMemoryLeak.java (added) +++ tomcat/trunk/test/org/apache/catalina/loader/TestWebappClassLoaderThreadLocalMemoryLeak.java Fri Mar 9 19:08:49 2012 @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.catalina.loader; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.apache.catalina.startup.TomcatBaseTest; +import org.apache.tomcat.util.buf.ByteChunk; +import org.junit.Test; + +public class TestWebappClassLoaderThreadLocalMemoryLeak extends TomcatBaseTest { + + @Test + public void testThreadLocalLeak() throws Exception { + + Tomcat tomcat = getTomcatInstance(); + + // Must have a real docBase - just use temp + Context ctx = tomcat.addContext("", + System.getProperty("java.io.tmpdir")); + + Tomcat.addServlet(ctx, "leakServlet", new LeakingServlet()); + ctx.addServletMapping("/leak1", "leakServlet"); + + Tomcat.addServlet(ctx, "leakServlet2", new LeakingServlet2()); + ctx.addServletMapping("/leak2", "leakServlet2"); + + tomcat.start(); + + // This will trigger the timer & thread creation + ByteChunk chunk = getUrl("http://localhost:"; + getPort() + "/leak1"); + System.out.print("First Threadlocal test response " + chunk.toString()); + + chunk = getUrl("http://localhost:"; + getPort() + "/leak2"); + System.out + .print("Second Threadlocal test response " + chunk.toString()); + + // Stop the context + ctx.stop(); + + // If the thread still exists, we have a thread/memory leak + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + // ignore + } + } + + class LeakingServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private ThreadLocal<MyCounter> myThreadLocal = new ThreadLocal<MyCounter>(); + + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, + IOException { + + MyCounter counter = myThreadLocal.get(); + if (counter == null) { + counter = new MyCounter(); + myThreadLocal.set(counter); + } + + response.getWriter().println( + "The current thread served this servlet " + + counter.getCount() + " times"); + counter.increment(); + } + + @Override + public void destroy() { + super.destroy(); + // normally not needed, just to make my point + myThreadLocal = null; + } + } + + class LeakingServlet2 extends HttpServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, + IOException { + + List<MyCounter> counterList = ThreadScopedHolder.getFromHolder(); + MyCounter counter; + if (counterList == null) { + counter = new MyCounter(); + ThreadScopedHolder.saveInHolder(Arrays.asList(counter)); + } else { + counter = counterList.get(0); + } + + response.getWriter().println( + "The current thread served this servlet " + + counter.getCount() + " times"); + counter.increment(); + } + } + + static class ThreadScopedHolder { + private final static ThreadLocal<List<MyCounter>> threadLocal = + new ThreadLocal<List<MyCounter>>(); + + public static void saveInHolder(List<MyCounter> o) { + threadLocal.set(o); + } + + public static List<MyCounter> getFromHolder() { + return threadLocal.get(); + } + } + + class MyCounter { + private int count = 0; + + public void increment() { + count++; + } + + public int getCount() { + return count; + } + } +} \ No newline at end of file --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org