Vinod Akkepalli
Vinod Akkepalli

Reputation: 169

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.

Upvotes: 0

Views: 126

Answers (2)

assylias
assylias

Reputation: 328598

Here is an example:

volatile int i:

public void m() {
  if (i == 0) i = 1;
  else i = 2;
}

You could have two threads check the condition, see that i is 0 and set it to 1, although one would expect that two runs of this method would set i to 2. This is a classical "check-then-act" scenario.

The problem is that volatility gives you a visibility guarantee but no atomicity guarantee.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500235

"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.

Upvotes: 1

Related Questions