[concurrency-interest] The very best CAS loop

Martin Buchholz martinrb at google.com
Tue Sep 27 14:18:59 EDT 2016


My proposal produces strictly cleaner, more compact source code and
bytecode, while maintaining the property that updateFunction will never be
called just because of a spurious weak cas failure, without loss of
performance, so ... COMMIT IS YES?

(ambitious Dice-style cas optimizations are a future project)

(I would even be OK with *specifying* that updateFunction will never be
called spuriously, but that's also a future project)

(Paul/Doug: is there a VarHandle equivalent to Atomic*.getAndUpdate?
Another future project?)

On Sat, Sep 24, 2016 at 9:51 AM, Martin Buchholz <martinrb at google.com>
wrote:

> 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.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20160927/fad661ad/attachment.html>


More information about the Concurrency-interest mailing list