Where as program needs to give out by upending all thread names from 0-4. But in above output Thread-0 is missing. When I make Map to Synchronized then it should be thread safe and all thread names must to added in Map value.
So any one let me know what is the issue in my code ?
Read the API for Collections#synchronizedMap(). The synchronized map ensures that a single method call is processed atomically (a get() or a set() call). It does not ensure that consecutive methods calls (a get() followed by a set()) will provide consistent data. And this is your problem. You have a get() (get the current value of "1") followed by a set() (set the value of "1" to the old value + a new string) followed by a get() (get the new value to print). These three steps are not performed atomically, and so are no guaranteed to be consistent. and that it what is happening. Some place in between Thread-0's get-set-get sequence, another thread is setting the value. As a matter of fact, the way it looks for that particular run, Thread-2 gets the value, then Thread-0 gets the value and sets the value, then Thread-2 sets the value and prints the value, then Thread-0 prints the value.
You need to add your own synchronization to ensure that block of code, which is required to be consistent, runs in an atomic fashion.
Anand Kumar Mmm
Joined: Mar 20, 2013
Thanks for reply.
Actually my question is at final after processing all 5 Threads then value in the Map must be with all Thread names. Its missing in my output.
You can see in
Where I can see Thread-1,2,3,4 and Thread-0 is missing the final value of Map.
Do I need to place synchronized block need to use for this?
Same reason as stated by Steve.
You are basically just printing the "last" iteration already printed by your Thread.
I think the Collections.synchronized... should be avoided in most cases because it implicates a kind of security which is simply not there.
Anand Kumar Mmm wrote:Where I can see Thread-1,2,3,4 and Thread-0 is missing the final value of Map.
Re-read my explanation. Use a pencil and paper to follow the execution sequence I described. It is what causes this problem.
Anand Kumar Mmm wrote:Do I need to place synchronized block need to use for this?
Yes, and use the map as the source for the synchronization lock.
Manuel Petermann wrote:I think the Collections.synchronized... should be avoided in most cases because it implicates a kind of security which is simply not there.
I wouldn't go that far. The synchronized collections provide memory consistency when accessing collections across multiple threads. They serve their purpose well and save me from having to maintain my own version of these same classes. People just have to read the documentation and use them correctly.
subject: HashMap to synchronized Map is not working