Why Volatile doesn't work when the value of a field depends on its previous value

I came across this statement, for which I could not think of a reason.

Volatile doesn't work when the value of a field depends on its previous value

Any explanation with example is highly appreciated.

Jon Skeet
people
quotationmark

"Doesn't work" is a pretty vague claim, but I suspect that the point is that if you have two threads each executing a loop with this code:

field = field + 1

... then even when it's volatile, each iteration is effectively:

  1. Read
  2. Perform computation with value we've read
  3. Write

If one thread performs the read, then another thread performs a write, then by the time the first thread performs its write, it will effectively be ignoring the second thread's write.

So going back to our example, if you have two threads each executing a million iterations of field = field + 1, the total increase in the value of field may not be two million.

people

See more on this question at Stackoverflow