I have read up on ThreadLocal, but still something about I find puzzling.
As I have understood it a ThreadLocal is shared between everyone within a thread. However O'Reilly Java Threads states that since ThreadLocal are declared static the object itself are shared among threads. And when get is called the internal mechanism of the ThreadLocal class returns the specific object assigned to the specific thread. But why need to shared the object among threads if only it is possible for current threads to get its own data and not others?
Lets say that in two seperate cases someone creates an instance of SecurityManager(and thus creates two ThreadLocal variables). Does they then not create two seperate ThreadLocal objects(Even if its just on thread running) ? So how can they both access the same data stored in that ThreadLocal. I just glanced at the source of ThreadLocal and the constructor is empty. But I guess that there can only exist one ThreadLocal for each Thread....
If you have only one thread would not two ThreadLocal variables access the same value store in thats threads ThreadLocal? [ July 27, 2007: Message edited by: Sverre Moe ]
Joined: Aug 03, 2004
The purpose of a thread local variable is that is has different values for different threads.
ThreadLocal implements this mechanism in Java. One instance of ThreadLocal stores different values for each thread.
The value of a ThreadLocal (ThreadLocal.get()) is determined by two factors: