Re: synchronized
John B. Matthews wrote:
If I may amplify, the new value must not depend on the previous value:
<http://www.ibm.com/developerworks/java/library/j-jtp06197.html?S_TACT=105AGX02&S_CMP=EDU>
To the OP: That link there talks about visibility, which is the other
issue. Synchronization does more in Java than just guarantee mutual
exclusion. It also manages where and when your variable(s) is visible to
other threads.
Imagine that you have, not just multiple threads, but multiple CPUs.
Each CPU has it's own cache internally. If you have one thread, reading
modifying and writing a variable it's possible that the variable is only
modified by the one CPU, and it's values never leave the caches.
Synchronization fixes this by forcing a cache flush or a write-through
when the mutex ends. You aren't just forcing exclusive access, you're
making sure the JVM knows the variable is used by multiple threads and
therefore need to be made visible to all threads each time you change it.
Volatile does this too, and so do the concurrent objects like
AtomicInteger.