Why @Volatile doesn't solve thread-safe counters

There is a common misconception about what volatile variables guarantee. So to understand when it's useful, we need to go back to considering the thread-safe counter from previous examples. During previous explanations, I indicated that the atomicity violations in the example happen because two threads read the value of a variable really close in time, which in turn causes some of the changes to be lost. But there's a little more to it; there can be two reasons why both threads read the same value:

  • When the reads of a thread happen during the reading or modifying of another thread: both threads start with the same data and make the same increment. Both change the counter from X to Y, so one increment is lost.
  • When the read of one thread happens after the modifying of another thread, but the cache local to the thread has not been updated: a thread can read the value of the counter as X even after another thread set it to Y because the local cache was not updated in time. The end result is similar: the second thread will increase the value of the counter, but since it started with an obsolete value, it will only override the change already made.
Notice that even though the cause is a little bit different, both of these situations have the same result: data changes being lost due to lack of synchronization.

As you can probably guess, volatile variables will offer protection in the second case, by making sure that any read of a state will always hold the most recent value. But they will not guarantee protection against the first case, because two threads can still read the current value close enough for them to try to perform the same increment, resulting in data loss.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.19.243