Java ThreadLocal static?

27,586

Solution 1

As per the definition of ThreadLocal class

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. 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).

That means say 2 threads t1 & t2 executes someBMethod() and they end up setting x1 & x2(Instances of X) respectively. Now when t1 comes and executes someCMethod() it gets x1 (which is set by itself earlier) and t2 gets x2.

In other words, its safe to have a single static instance of ThreadLocal, because internally it does something like this when you invoke set

set(currentThread, value) //setting value against that particular thread

and when you invoke get

get(currentThread) //getting value for the thread

Solution 2

I study the java source code,

  1. java.lang.Thread Class contains a instance variable as below.

    ThreadLocal.ThreadLocalMap threadLocals = null;

Because threadLocals variable is non-static, Every thread in a application (i.e., every instance of Thread Class) will have it's own copy of threadLocals map.

  1. Key for this map is, current ThreadLocal instance, and value is the value which you pass as argument to ThreadLocal.set().

  2. When you try to fetch value as ThreadLocal.get() , internally, it will fetch from the ThreadLocalMap of Current Thread.

In simple terms, you are getting & setting values from/to your current Thread Object, not from/to your ThreadLocal object.

Solution 3

Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal

Yes, they operate on the same object. However, it is important to realize that the way ThreadLocal works is that each thread has its own, separate value. Thus if you have ten threads writing to myThreadLocal and then reading from myThreadLocal, each will see the correct (i.e. their own) value.

To put it another way, it does not matter which class or object writes to an instance of ThreadLocal. What matters is the thread in whose context the operation is performed.

Solution 4

No they won't, thats the point. Javadoc :

These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. 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).

Solution 5

Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal

No they won't. Every thread has its own instance of the contained variable of type X.

thereby beating the very purpose of ThreadLocal variable

No.

Have another look at the Javadoc.

Share:
27,586

Related videos on Youtube

Jasper
Author by

Jasper

Areas of interest and skill: Java / J2EE / MongoDB / Big Data/ Hadoop / Machine Learning / Cloud / Amazon EC2

Updated on July 09, 2022

Comments

  • Jasper
    Jasper almost 2 years

    Setting a value in Thread Local:

    //Class A holds the static ThreadLocal variable.
    
        Class A{
    
        public static ThreadLocal<X> myThreadLocal = new ThreadLocal<X>();             
        ....
        }
    
    
    //A Class B method sets value in A's static ThreadLocal variable 
        class B{
        {
             public void someBmethod(){
                 X x = new X();
                 A.myThreadLocal.set(x);
             }
        }
    
    
    //Class C retrieves the value set in A's Thread Local variable.
    
        Class C {
    
        public void someCMethod(){
             X x = A.myThreadLocal.get();
        }
        ...
        }
    

    Quesiton:
    Now assuming this is a web-application, and threads execute: B.someBMethod, C.someCMethod in that order.

    Multiple threads executing B's someBMethod, will end up updating the SAME A's static ThreadLocal variable myThreadLocal, thereby beating the very purpose of ThreadLocal variable. (Using static for ThreadLocal is what is recommended as per documentation.)

    The C's someCMethod, while retrieving value from ThreadLocal may not get the value set by the 'current' thread.

    What am i missing here?

  • TechDog
    TechDog over 7 years
    The need for this class is crucial while creating thread specific singleton objects....
  • Angel O'Sphere
    Angel O'Sphere almost 6 years
    The Java Doc is extremely unclear, hence he asked that question, and hence why I'm here reading the questions and answers :D
  • user207421
    user207421 over 3 years
    The very name ThreadLocal answers your question, let alone the Javadoc. The extract provided by @NimChimpsky alone is sufficient.