Day: 23 September 2008

ThreadLocal and Thread Pools

ThreadLocal is a mechanism that can be used to put data onto a thread so that it can be accessed from any code using that thread. One use is to make contextual information relevant to the current thread available throughout the stack trace, for example a transaction context, or security context. If you use it yourself, you need to watch out if the environment in which it runs gets its threads from a thread pool (e.g. if your application runs in a managed container such as in an app server). Typically a thread pool gives no guarantee that the ThreadLocal (or indeed other internal state) will be cleared next time the thread is taken from the thread pool. This means you could have an issue  - consider this case: Two web applications deployed in the same EAR (or even seperate EARs depending upon your class loader configuration and deployment) - both set a thread local which is a map (key / value pairs). One application, in a given case, processing a web request doesn't set a value in the map and calls a service which reads that unset value using a key (the same key is used within both applications). Instead of being unset (null / empty), that unset value could be a value from the other application, if the thread is not new and your code does not clean up the thread local before returning the thread to the pool. I did some tests and these were the results:…

Read more