I agree with the above posts by Jim And Ulf. Going back to the original post I would add:
Sahil Kapoor wrote:Problem:- Is a single java statement atomic ???
In general, no. Some are, but many are not.
You should never assume that a statement is atomic - you should
know why that
particular statement is atomic, or you should assume it isn't.
Sahil Kapoor wrote:Problem2 :- But we need to synchronize a code having just one for loop. ???
Sometimes, yes -
even if all the individual statements in the loop are atomic. Because if you have two or more atomic statements, stuff can still happen
in between those two statements. That's why even with a Vector or Collections.synchronizedList(), you can't safely iterate the list without additional synchronization. It's pretty difficult to do
anything useful with one of these without additional synchronization, really. Which is why I consider them inherently evil, as they just mislead people into thinking that they're "thread-safe" just because they're "synchronized". To use synchronization effectively, you usually need to make sure the synchronization wraps around whatever
group of statements you need to be protected from interference.