In short – tomcat uses a thread pool, so threads are reused. Some libraries use ThreadLocal variables, but don’t clean them up (using .remove()), so in fact they return “dirty” threads to the pool.
Tomcat has new features of detecting these things on shutdown, and cleaning the thread locals. But it means the threads are “dirty” during the whole execution.
What I can do is implement a Filter, and right after the request completes (and the thread is returned to the pool), clean all ThreadLocals, using the code from tomcat (the method there is called checkThreadLocalsForLeaks).
The question is, is it worth it? Two pros:
- preventing memory leaks
- preventing undeterministic behaviour by the libraries, which assume the thread is “fresh”
One con:
- The solution uses reflection, so it’s potentially slow. All reflection data (
Fields) will be cached, of course, but still.
Another option is to report the issue to the libraries that don’t clean their thread locals.
I would go through the route of reporting the issue to the library developers for 2 reasons:
Honestly, I’ve never seen this type of error before and I think it’s an exception rather than something that we should guard as it happens often. Could you share on which library you’ve seen this behaviour?
As a side note, I wouldn’t mind enabling that filter in the development / test environment and logging a critical error if a ThreadLocal variable is still attached.