This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Jelle Klap wrote:
Edit: Ugh ninja'ed by Henry ;)
Dmitry Zhuravlev wrote:
So actually this looks like a special static variable that can have many instances per class..
apigee, a better way to API!
ramesh vanka wrote:ThreadLocal instance associated Thread,
run(){
ThreadLocal a = new ThreadLocal();
a.set(Thread.currentThread().getName());
}
Two threads t1,t2 threads are running.
T1 Scenario:
ThreadLocal internally maintain map. In map(KEY, VALUE) ,
KEY = THREAD IDENTIFIER,Based thread hashcode and some logic, it will generate the Thread Identifier
Value= a.set(Thread.currentThread().getName());
so when ever T1 issues t1.get(), first it will check internal map, In the map it have thread identifier it will give the value.
T1 Scenario:
Same like that.
Hope It will clear the doubts.
Eduardo Moranchel wrote:The way i understand it:
A thread local is a class.
It has a value per thread.
It is a key/value store where the key is the Thread ID and the value is whatever we put inside
Wait. is it... like a map?
maybe. lets think it this way.
All threads have a unique ID, that can be the key of the map.
And we store a value inside.
So we can say a ThreadLocal can be actually a Map<ThreadId, ValueType> variable.
but handling maps and stuff is bad and boring so why not disguise it with ThreadLocal<ValueType>
ok now then how do we get the id?
Thread.getCurrentThread().getId ? something like that exists actually.
So there you have it. how ThreadLocals work.
New rule: no elephants at the chess tournament. Tiny ads are still okay.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|