|
From: Andy D. <an...@ma...> - 2005-06-15 20:43:20
|
Many times ThreadLocal is used to maintain information concerning the current
call stack, with that information being discarded as the stack unwinds. The
basic idea is effectively like this:
((SomeStack)threadLocal.get()).push(info);
try {
...
} finally {
((SomeStack)threadLocal.get()).pop();
... code to clean up threadLocal if empty stack ...
}
ThreadLocals come in handy when you want code in a particular call stack to
have access to context information that can't be passed around as parameters.
Transactions, security, auditing, etc, are all examples of things that often
utilize ThreadLocals for the duration of a single "call stack". In my mind,
this particular pattern should be resilient to the effect described in the
blog. The pattern looks something like this (pseudo flow):
1. Request comes in from client
2. J2EE container pulls a thread from the pool to handle request
3. J2EE container eventually invokes Spring based code which happens to use
Spring for transaction management.
4. Spring sets up transaction context in a ThreadLocal.
5. Spring based code invokes various service beans (which in turn can invoke
other service beans), utilizing the ThreadLocal transaction context for
transaction management.
6. Spring based code finishes, Spring cleans up ThreadLocal and returns to the
J2EE Container.
7. J2EE Container puts thread back in pool, possibly wiping ThreadLocals.
The one thing developers need to be careful of in this usage pattern is
properly cleaning up ThreadLocals (for security reasons) before returning
control to the J2EE container.
Where I see a problem is if any code expects ThreadLocal to survive between
client requests (if using the above example). The only other problem would
be if Spring code happens to invoke some interface that jumps threads:
a. Spring code invokes EJB interface
b. Container decides to handle invocation in another thread.
c. Spring code is blocked while other thread handles invocation.
- This other thread has no access to ThreadLocal contextual information
from calling thread.
d. Other thread finishes.
e. Container wakes up original thread, passing in the return value.
As silly as this seems, it can happen in practice depending on the
architecture of the system.
As long as Spring sticks to this usage pattern, then I'm not seeing a problem
- or am I missing something?
- Andy
On Wednesday 15 June 2005 01:01 pm, Tim Kettering wrote:
> This guy (presumably a senior dev @ IBM) says not to use ThreadLocal. He
> says that usage should be removed from open-source projects (mentioning
> Spring specifically).
>
>
>
> Wanted to pass this url on - see what you Spring developers thought about
> this.
>
>
>
> http://www.devwebsphere.com/devwebsphere/2005/06/dont_use_thread.html
|