views:

122

answers:

3

I'm using ThreadLocal variables (through Clojure's vars, but the following is the same for plain ThreadLocals in Java) and very often run into the issue that I can't be sure that a certain code path will be taken on the same thread or on another thread. For code under my control this is obviously not too big a problem, but for polymorphic third party code there's sometimes not even a way to statically determine whether it's safe to assume single threaded execution.

I tend to think this is a inherent issue with ThreadLocals, but I'd like to hear some advise on how to use them in a safe way.

+6  A: 

Then don't use ThreadLocals! They are specifically for when you want a variable that's associated with a Thread, as if there were a Map<Thread,T>.

Jonathan Feinberg
The answer is so simple! I’d +1 you but unfortunately I’m all out of votes for today.
Bombe
A: 

If you require a method to be run only by a single thread at a time, why not just mark it syncronized? Otherwise, ThreadLocals are only there for very specific use cases and should only be used sporadically.

Romain
A: 

The typical use case (as far as I know) for a ThreadLocal is in a web application framework. An HTTP filter obtains a database connection on an incoming request, and stores the connection in a static ThreadLocal. All subsequent controllers needing the connection can easily obtain it from the framework using a static call. When the response is returned, the same filter releases the connection again.

Adriaan Koster