• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is ThreadLocal?  RSS feed

 
vijay shanker
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is quite unusual question as the term in itself defines the whole context. But what i mean to know is this variable will be local for all the child threads.

If i have got a Thread Local variable it will be local for all the classed evoked by this particular thread.
 
Adam Michalik
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ThreadLocal is, just as the name suggests, a variable local to the currently executing thread. So it won't be inherited by any thread spawned by this thread. Nor will it be local to any classes (classes are not bound to threads in any way). When object O's method executes in thread A, it will use A's ThreadLocal. When in thread B - B's.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Technically that's not correct. It will use the same ThreadLocal object. It will however, use a different object stored in that ThreadLocal object.

Simply put, you can see the ThreadLocal object as a mapping from threads to objects. When you call get() from a thread, it will look up the object for that thread only. If get is called for the first time for a thread, it will call initialValue(). Similarly, put(value) will add the given value for the current thread, overwriting the current value.

The following code is how ThreadLocal could be implemented:
ThreadLocal isn't implemented exactly like this, but it works as if it was.
 
Gaurav Purandare
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry I am new to this,
From what Rob said ThreadLocal seems more like a design pattern.

Is that correct?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ThreadLocal isn't implemented exactly like this, but it works as if it was.


A similar topic came up recently, and I said almost the same thing... it really "isn't implemented exactly like this", and to my surprise, it is completely "isn't like this"...

Basically, the ThreadLocal class doesn't really store the values. With the exception of an atomic int that it uses to calc hashcodes, it has no storage at all. Instead, the values are actually stored in the corresponding Thread class -- with a weak reference back to the ThreadLocal so that the values may be GC'ed with the matching thread local.

Henry

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!