| Author |
get and initialValues method of ThreadLocal synchronized
|
Krishnaa Kumar
Greenhorn
Joined: May 05, 2011
Posts: 25
|
|
Hi,
I came across a code where the get() and initialValue() methods of ThreadLocal is synchronized.
I couldn't find any use of having these methods synchronized. Correct me if I am wrong.
-Krishna.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
ThreadLocal's own get and initialValue methods are not synchronized. If the (sub) class you saw has them synchronized, there may be some additional code inside them that requires synchronization. Without seeing that code we won't be able to tell.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Krishnaa Kumar
Greenhorn
Joined: May 05, 2011
Posts: 25
|
|
Hi.,
Basically we make methods synchronized to avoid concurrent update of a value in the method definition.
Thus the updated value by one thread is radiated to all threads.
But, in ThreadLocal concept, each thread has its individual independent value.
At any point of time no two threads access a same threadLocal value. then why to make initialValue method synchronized?
-Krishna.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
Each thread has its own value, true, but the get and initialValue method are both called on the one thread local object. That means that if the get and/or initialValue method accesses some of the state variables (other than the thread-to-value map), they still need synchronization.
|
 |
 |
|
|
subject: get and initialValues method of ThreadLocal synchronized
|
|
|