| Author |
What is ThreadLocal?
|
vijay shanker
Ranch Hand
Joined: Oct 26, 2007
Posts: 88
|
|
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
Joined: Feb 18, 2008
Posts: 128
|
|
|
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
Joined: Oct 27, 2005
Posts: 19216
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Gaurav Purandare
Greenhorn
Joined: Apr 06, 2009
Posts: 19
|
|
Sorry I am new to this,
From what Rob said ThreadLocal seems more like a design pattern.
Is that correct?
|
Gaurav
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16688
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: What is ThreadLocal?
|
|
|