• Post Reply Bookmark Topic Watch Topic
  • New Topic

get and initialValues method of ThreadLocal synchronized  RSS feed

 
Krishnaa Kumar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Krishnaa Kumar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!