[concurrency-interest] The very best CAS loop

Dávid Karnok akarnokd at gmail.com
Sat Sep 24 16:34:13 EDT 2016


Isn't the second one getting 2 safepoint polls when the weak CAS failed due
to different actually changed value?

2016-09-24 18:51 GMT+02:00 Martin Buchholz <martinrb at google.com>:

> Discussion on CAS loops got me looking again at our own:
>
>     public final V getAndUpdate(UnaryOperator<V> updateFunction) {
>         V prev = get(), next = null;
>         for (boolean haveNext = false;;) {
>             if (!haveNext)
>                 next = updateFunction.apply(prev);
>             if (weakCompareAndSetVolatile(prev, next))
>                 return prev;
>             haveNext = (prev == (prev = get()));
>         }
>     }
>
> The haveNext boolean and useless initialization of next bothers me.  We
> can do better!
>
>     public final V getAndUpdate(UnaryOperator<V> updateFunction) {
>         for (V prev = get();;) {
>             V next = updateFunction.apply(prev);
>             do {
>                 if (weakCompareAndSetVolatile(prev, next))
>                     return prev;
>             } while (prev == (prev = get()));
>         }
>     }
>
> even though it probably saves more bytecodes than cycles.
>



-- 
Best regards,
David Karnok
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20160924/b5657f4f/attachment.html>


More information about the Concurrency-interest mailing list