[concurrency-interest] The very best CAS loop

Martin Buchholz martinrb at google.com
Sat Sep 24 12:51:43 EDT 2016


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/20160924/5ca87df9/attachment.html>


More information about the Concurrency-interest mailing list