| Author |
Some ThreadLocal issues
|
Sverre Moe
Ranch Hand
Joined: Jul 10, 2007
Posts: 109
|
|
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? When a class SecurityManger(for example) defines private static ThreadLocal threadLocal = new ThreadLocal(); 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 ]
|
 |
Vlado Zajac
Ranch Hand
Joined: Aug 03, 2004
Posts: 244
|
|
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: ThreadLocal instanceand current thread
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
|
I've just been busy explaining ThreadLocal in this thread, including something of the implementation. It's not really so complicated!
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: Some ThreadLocal issues
|
|
|