[concurrency-interest] atomicity and volatile

Tim Peierls tim at peierls.net
Wed Mar 5 19:18:27 EST 2008


Yes, you're correct.

On Wed, Mar 5, 2008 at 7:09 PM, Dhanji R. Prasanna <dhanji at gmail.com> 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
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20080305/81bf64d4/attachment.html 


More information about the Concurrency-interest mailing list