[concurrency-interest] atomicity and volatile

Bill Pugh pugh at cs.umd.edu
Wed Mar 5 19:14:16 EST 2008


Yep.

Don't do that.

Use AtomicInteger instead. Or use some form of locking/synchronization.

Bill Pugh

On Mar 5, 2008, at 7:09 PM, Dhanji R. Prasanna wrote:

> Hi I have a volatile field being incremented by multiple threads:
>
> public class MyCounter {
>     private volatile int count;
>
>     public void increment() {
>          count++
>     }
>
> }
>
> Am I correct in assuming that multiple threads could clobber each  
> others increments since count++ is not an atomic operation relative  
> to all threads calling increment? Even though the value of count is  
> coherent between threads when it is read...
>
> So for instance:
>
> thread A enters increment(), reads count as 0
> MEANWHILE thread B enters increment(), also reads 0 in count (since  
> thread A has not yet set count to 1) and writes 1 to count.
> thread A overwrites the value in count (which is already 1) with 1.
>
> Therefore thread A clobbers thread B's increment work. Does that  
> make sense?
>
> Dhanji.
> _______________________________________________
> 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