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?