[concurrency-interest] Unsafe.getAndAddLong

Arcadiy Ivanov arcadiy at ivanov.biz
Thu May 22 10:29:48 EDT 2014

JLS 17.4.7


    Each read sees a write to the same variable in the execution.

    All reads and writes of volatile variables are volatile actions. For
    all reads/r/in/A/, we have/W(r)/in/A/and/W(r).v/=/r.v/. The
    variable/r.v/is volatile if and only if/r/is a volatile read, and
    the variable/w.v/is volatile if and only if/w/is a volatile write.

If you have a volatile write but no volatile read, there is no guarantee 
that there won't be a reordering occurring. As such, the compiler may 
optimize the first read away and you'll be left with a value that has 
been read quite a long time ago earlier potentially all the way to the 
previous CAS.

I would add another clause:
(3) Ensuring that the first read of v is not reordered.

But the worst case scenario you would have is that you'll have a failing 
CAS the first time so both reordering and stale cache are technically 
covered under my (1).

On 2014-05-22 10:14, Andrew Haley wrote:
> How does getLongVolatile help the first read of 'v' to be up to date?
> HotSpot emits an acquire barrier after reading 'v'.
> On 05/22/2014 03:10 PM, Arcadiy Ivanov wrote:
>> (1)To increase the chance that the first CAS will succeed.
>> (2)To ensure that both 32bit words of a 64bit long are read atomically.
>> Otherwise there is a pretty good chance the first CAS will fail due to
>> 'v' either not being up-to-date or being nonsensical due to non-atomic
>> read of non-volatile longs and doubles.
>> On 2014-05-22 09:55, Andrew Haley wrote:
>>> More memory model mysteries:
>>> Why do we use getLongVolatile here?  It'll be a load followed by an
>>> acquire barrier.  But compareAndSwapLong is in effect a full barrier
>>> anyway, so what's the point of using getLongVolatile?
>>>       public final long getAndAddLong(Object o, long offset, long delta) {
>>>           long v;
>>>           do {
>>>               v = getLongVolatile(o, offset);
>>>           } while (!compareAndSwapLong(o, offset, v, v + delta));
>>>           return v;
>>>       }
>>> Andrew.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140522/52994f5c/attachment.html>

More information about the Concurrency-interest mailing list