I’m trying to understand synchronization of multiple threads in Java more fully. I understand the high level idea behind the use of the synchronized keyword, and how it provides mutual exclusion among threads.
The only thing is that most of the examples I read online and in my textbook still work correctly even if you remove the synchronized keyword which is making this topic more confusing than I think it needs to be.
Can anyone provide me with a concrete example of when not including the synchronized keyword will produce erroneous results? Any information would be much appreciated.
You can usually trigger a race condition by increasing the number of iterations. Here’s a simple example that works with 100 and 1,000 iterations but fails (at least on my quad-core box) at 10,000 iterations (sometimes).
This example fails because access to
counteris not properly synchronized. It can fail in two ways, possibly both in the same run:The fix for this simple program would be to use an
AtomicInteger. Usingvolatileisn’t enough due to the problem with increment, butAtomicIntegerprovides atomic operations for increment, get-and-set, etc.