On 23 nov. 2011, at 16:48, Christopher Schultz wrote: > Our servlet defines the ThreadLocal to be protected (because this is a > base class for several servlets that all do similar things) and > transient (because we just don't need it to be serialized) and > override the initialValue method, like this: > > protected transient ThreadLocal<SimpleDateFormat> dayFormat = new > ThreadLocal<SimpleDateFormat>() { > public SimpleDateFormat initialValue() > { > return new SimpleDateFormat("yyyy-MM-dd"); > } > }; > > In the servlet's destroy method, we dutifully call dayFormat.remove(). > Tomcat complains that we are leaving sloppy ThreadLocals around on > shutdown. Duh: Servlet.destroy is called by a single thread and won't > actually remove the ThreadLocal in any meaningful way. > So, my question is whether or not there is a good way to clean-out the > ThreadLocals from our webapp? > > Given the declaration above, we are creating a new class which will be > loaded by our webapp's ClassLoader and therefore pinning that > ClassLoader in memory definitely causing a memory leak across reploy > cycles.
I don't think this ThreadLocal creates a real leak of classloader. It would if dayFormat was static. But you may still see warnings issued by tomcat when the application is stopped because of this problem http://wiki.apache.org/tomcat/MemoryLeakProtection#threadLocalPseudoLeak After some time and if all the threads of the server are sollicited sufficiently, the classloader will be eventually collected. With tomcat 7, there's no leak since threads are renewed, but you might still see the warnings. IMHO, you'd rather either stop worrying and recreate a new SimpleDateFormat, unless actual tests show a real bottleneck. In that case, go with another implementation like FastDateFormat. It will be much cleaner than playing with ThreadLocals... Sylvain --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org For additional commands, e-mail: users-h...@tomcat.apache.org