This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes get and initialValues method of ThreadLocal synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "get and initialValues method of ThreadLocal synchronized" Watch "get and initialValues method of ThreadLocal synchronized" New topic
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: get and initialValues method of ThreadLocal synchronized
 
Similar Threads
What is ThreadLocal
Bug in SimpleDateFormat? Is that you also experienced?
Are spring beans thread-safe?
ThreadLocal member
when are static ThreadLocal variables intialized