[concurrency-interest] AtomicReference.updateAndGet() mandatory updating
Justin Sampson
jsampson at guidewire.com
Tue May 30 03:47:32 EDT 2017
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