Why Java ThreadLocal Variables Should Be Static

I read JavaDoc for Threadlocal here

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

and that says, “ThreadLocal examples are typically private static fields in classes that want to associate state with a thread (such as a user ID or transaction ID).

But my question is why did they decide to make it static (usually) - does it make things a bit confusing in order to have a "for stream" state, but the fields are static?

+79
java multithreading
May 6 '10 at 19:54
source share
5 answers

Because if it were an instance level field, it would actually be a “Per Thread - Per Instance”, and not just a guaranteed “Per Thread”. This is usually not the semantics you are looking for.

Usually it holds something like objects that are tied to a user dialog, web request, etc. You do not want them to be subordinate to the class instance either.
One web request => one save session.
Not one web request => one persistence session for each object.

+93
May 6, '10 at 20:01
source share

Either make it static, or if you are trying to avoid static fields in your class - make the class single, and then you can safely use the ThreadLocal instance level if you have this singleton available all over the world.

+13
Feb 07 '12 at 7:12
source share

It's not obligatory. The important thing is that he should be single.

+9
May 6 '10 at 11:58
source share

The reason is that variables are accessed through a pointer associated with the stream. They act as global variables with a flow region, so the static is closest. This is the way you get the local state of the thread in things like pthreads, so it may just be a coincidence of history and implementation.

+3
May 6, '10 at 20:01
source share

Using threadlocal for each instance per thread is what you want something to be visible in all methods of the object and ensure its thread safety without synchronizing access to it, as for a regular field.

0
Jan 11 '13 at 21:33
source share



All Articles