I would like to add my answer to this question, even if it is old. I ran into the same problem (gson threadlocal was not removed from the request stream), and even got a convenient server reboot at any time when it ran out of memory (which takes a long time!).
In the context of a java web application installed in dev mode (the server is set up to fail every time it perceives a code change and, possibly, also works in debug mode), I quickly found out that threadlocals might be awesome someday to be a pain. I used threadlocal Invocation for each request. Inside Invocation. Sometimes I also used gson to generate my answer. I would wrap Invocation inside a try block in a filter and destroy it inside a finally block.
What I observed (at the moment I have no indicators for backup), I added that if I made changes to several files and the server constantly bounced between my changes, I would become impatient and restart the server (tomcat to be exact ) from the IDE. Most likely, I would end the "Out of memory" exception.
As I got around this, I need to include the ServletRequestListener application in the application, and my problem disappeared. I think what happens is that in the middle of the request, if the server fails several times, my threadlocals are not cleared (including gson), so I get this warning about threadlocals and two or three warnings later, the server crashes. When the ServletResponseListener explicitly closes my threadlocals, the gson problem disappeared.
Hope this makes sense and gives you an idea of how to overcome threadlocal related issues. Always cover them around your point of use. In the ServletRequestListener, check each threadlocal wrapper and, if it still has a valid reference to some object, destroy it at that point.
I should also indicate what makes it a habit to wrap threadlocal as a static variable inside the class. This way you can be sure that by destroying it in the ServeltRequestListener, you do not have to worry about other instances of the same class hanging around.
mainas Jun 05 '13 at 6:45 2013-06-05 06:45
source share