5

I noticed something interesting.

I was told (and from what I read) that it is safe to hold request-scope variables in a ThreadLocal (let's say you don't have access to the request object and can't use request attributes)

Well, it seems to work (at least when I checked in tomcat). e.g. Even if I have 10 threads in the pool, the thread local variables seem to live only for the scope of a single request. I mean, even if I see the same thread name (let's say I have 10 in the pool, so after 10 requests I'm ought to see some repeat) each request "magically" resets all thread local variables for that thread.

Is that true?

Is every time a request thread is returned to the pool, it clears all thread local vars? How?

Eran Medan
  • 44,555
  • 61
  • 184
  • 276
  • Perhaps related: http://stackoverflow.com/questions/7403809/java-cached-thread-pool-and-thread-local –  May 01 '15 at 18:27
  • This will be container-dependent. The principle of the [ThreadLocal](https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html) dictates that the structure is reusable. How a specific container goes about it is up to that container – kolossus May 01 '15 at 18:29

2 Answers2

2

Later tomcat versions have a thread local protection mechanism to avoid memory leaks and especially defend against hanging class loaders on application re-deploy.

TC 6.0.24 detects it and 7.0.6 removes the thread locals, as documented here: http://wiki.apache.org/tomcat/MemoryLeakProtection

So this is not normal for threads/threadpools, but a TC feature.

eckes
  • 10,103
  • 1
  • 59
  • 71
1

Is every time a request thread is returned to the pool, it clears all thread local vars?

It seems that Tomcat took care of house-cleaning but in general the answer is No, and this was one of the reason that was causing Out Of Memory errors in Glassfish 3.0.1

In Glassfish 3.0.1, for instance during application deployment some code was creating a ThreadLocal variable holding a reference to some instances which in turn seems to hold a reference to a lot of other objects (mostly related to proxy classes generated during EJB and CDI deployment). Glassfish doesn't seem to clean this reference after the deployment finishes, which wouldn't be much of a problem if the thread that deploys the application terminates.

Unfortunately the application deployment thread never dies, because it is not created solely for the purpose of application deployment. It is instead taken from the Glassfish thread pool and expected behaviour is returned to the pool once it finishes the deployment task. That means the ThreadLocal reference never gets cleaned and over time causes the heap to overflow.

sol4me
  • 15,233
  • 5
  • 34
  • 34