views:

153

answers:

3

I was reading that JavaDoc for Threadlocal here

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html

and it says "ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID). "

But my question is why did they choose to make it static (typically) - it makes it a bit confusing to have "per thread" state but its static?

+5  A: 

Because if it were an instance level field, then it would actually be "Per Thread - Per Instance", not just a guaranteed "Per Thread." That isn't normally the semantic you're looking for.

Usually it's holding something like objects that are scoped to a User Conversation, Web Request, etc. You don't want them also sub-scoped to the instance of the class.
One web request => one Persistence session.
Not one web request => one persistence session per object.

Affe
I like this explanation because it shows how ThreadLocal is to be used
kellyfj
+3  A: 

The reason is that the variables are accessed via a pointer associated with the thread. They act like global variables with thread scope, hence static is the closest fit. This is the way that you get thread local state in things like pthreads so this might just be an accident of history and implementation.

Ukko
A: 

It doesn't have to be. The important thing is that it should be a singleton.

irreputable