[concurrency-interest] How bad can volatile long++ be?

Chris Purcell chris.purcell.39 at gmail.com
Mon Dec 10 13:04:10 EST 2007

I can't answer with authority whether ++ is atomic; I don't believe
so. However, I can answer the rest of the question.

The reads and writes will be atomic. Even so, the non-atomicity of the
increment may still result in a wildly wrong number being produced.

As an example, consider two threads incrementing a shared counter like
this a thousand times each. If the counter starts at zero, in one
unlikely but possible execution history, the final value of the
counter may be only 2. That is, one thousand nine hundred and ninety
eight increments can be lost. (The same final value is possible for
any number of threads and any number of increments.)

If you're only maintaining statistics, however, the inaccuracy of the
counter shouldn't be an issue.


On 12/10/07, Sam Berlin <sberlin at gmail.com> wrote:
> Hi Folks,
> I'm fairly certain that ++ is not an atomic operation, even on
> volatile variables, on longs (and quite possibly ints).  Given that is
> true (which it very well might not be), is it suspectible to problems
> where a wildly wrong number can be produced (due to different bytes
> being updated at different times from different threads), or will it
> just cause some increments to effectively not happen?
> Thanks!
>  Sam
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest

More information about the Concurrency-interest mailing list