[concurrency-interest] AtomicReference.updateAndGet() mandatory updating

Alex Otenko oleksandr.otenko at gmail.com
Tue May 30 04:42:58 EDT 2017


Racy reads can’t observe just any writes, only those that won’t contradict the happens-before partial order.

So you still need a write of 0 that you can place after the write of 1 in Thread 1. The initial write of 0 can’t be observed after any write observed after Thread 1 start.


Alex

> On 30 May 2017, at 08:47, Justin Sampson <jsampson at guidewire.com> wrote:
> 
> Alex Otenko wrote:
> 
>> int x=0; // non-volatile
>> volatile int z=0;
>> volatile boolean b=false;
>> 
>> Thread1:
>> if (CAS(z, 0, 1)) {
>>   if (x == 0) {
>>     b=true;
>>     CAS(z, 1, 2);
>>   }
>> }
>> return x;
>> 
>> Thread2:
>> x=1;
>> if (!CAS(z, 0, 2)) {
>>   return b;
>> }
>> return true;
> 
> I keep going over this code in my head. The data race is tricky.
> 
> In particular, the conclusion that "if Thread2 returns false then Thread1 returns 1" seems to rely on an assumption that if the read of x in "x == 0" sees 1 then the read of x in "return x" will also see 1. What part of the JMM justifies that assumption? Both reads are racy, _unless_ the first read does _not_ see 1. If the first read _does_ see 1, then the second read is still racy and it's possible for it to see 0. Non-volatile reads can be reordered freely, can't they?
> 
> Cheers,
> Justin
> 
> 



More information about the Concurrency-interest mailing list