On 1/26/2012 10:38 AM, Mark Thomas wrote:
OK. ThreadLocals have no place in a web application. Period. If a
programmer insists on using them, then it is their responsibility to
clean up the mess they leave behind.

Tomcat's memory leak detection and prevention code goes some way to
clearing up things like this but it is never going to cover every case.

Mark
Or put another way, you have a choice:

1. Use ThreadLocals the way you'd have assumed you could, but don't
   expect to ever restart your web app without leaking tons of memory.
2. Use ThreadLocals, but be sure you religiously clean up after
   yourself by the time your web app is fully shut down.
3. Don't use ThreadLocals.

If you use someone else's library that uses ThreadLocals then you'll probably end up in forced into A.

That said, there could and arguably should be another choice:

4. Select a special mode in a servlet engine that shuts down all
   threads that have ever serviced requests for a given web app when it
   is shutdown (and code your web app to shutdown any threads it
   creates, obviously!), e.g. after they complete servicing any request
   in progress.  [It could just replace all request threads with new
   ones after the requests currently in progress complete.]

That's assuming the servlet engine is nice enough to provide such a mode. If it did, however, I believe that would resolve any ThreadLocal issues without one having to avoid using a perfect natural and useful Java language feature. I'd argue all servlet engines should really provide this feature for just this reason. That said, I can live with A.

--
Jess Holle

Reply via email to