• Post Reply Bookmark Topic Watch Topic
  • New Topic

Some ThreadLocal issues  RSS feed

 
Sverre Moe
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 instance
  • and current thread

  •  
    Ernest Friedman-Hill
    author and iconoclast
    Sheriff
    Posts: 24215
    37
    Chrome Eclipse IDE Mac OS X
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I've just been busy explaining ThreadLocal in this thread, including something of the implementation. It's not really so complicated!
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!