Tuesday, September 4, 2007

Thread Local: A Convenient Abomination.

A couple of weeks ago i tried to find a storage place for sessioncontext(s)  so that one WinForms application could have multiple sessions open at a time. I noticed that there are no easy solutions for that problem. Today i read an article that describes the other side of the coin.

Thirteen years ago, while working on my first book, Jim Coplien and I were having a debate on the nature of threads and objects. He made a clarifying statement that has stuck with me since. He said: “An object is an abstraction of function. A thread is an abstraction of schedule.”

It has become the norm, in Java applications, to assume that there is a one-to-one correspondence between a thread, and a unit-of-work. This appears to make sense since every Servlet request has it’s own particular thread. Framework authors have built on this assumption by putting unit-of-work related information (e.g. session) into ThreadLocal variables.

Clearly, the more ThreadLocal variables that hold unit-of-work related information, the more that the thread and the unit-of-work are related. While very convenient, the basic assumption is dead wrong.

It doesn't matter if you have 1 or 10 threads. The problem is always the same. UnitOfWork or SessionState should have a place that does not depend on threads. It's a dangerous assumption that UnitOfWork is directly related to one single thread. That assumption seriously limits your other architectural choices. 

So, though convenient, ThreadLocal variables confuse the issue of separating function from schedule. They tempt us to couple function and schedule together. This is unfortunate since the correspondence of function and schedule is weak and accidental.

What we’d really like is to be able to create UnitOfWorkLocal variables.

Couldn't agree more.

 

Technorati Tags: