JavaFunda wrote:Roughly speaking, the first time a thread reads a shared (or potentially shared) variable after entering a sync block or method, it must read it from the main copy. Additionally, upon exiting the sync block/method, the thread must write any shared variables that has changed locally back out to the main copy. The actual rules are more complex than that, but that's more or less what it amounts to. Within the body of the sync block/method, however, threads are free to use local copies for shared variables as much as they want. It's only the entry/exit boundaries that matter.
Does synchronized methods internally write to main memory (i mean they dont keep the local copy )? so no need of declaring the shared variable as volatile, if operation on shared variable is occuring under synchronized methods/blocks. Is it correct?
EJP wrote:Correctness is almost always more important than performance. Performance counters the only example I can think of when performance is more important than correctness.You shouldn't need to worry that using a synchronized block will slow down access to dataI don't think he is, and worrying about the difference between a correct result and an incorrect result is futile. You can get the wrong answer in zero time if you want it.