[concurrency-interest] Composite compare-and-swap based on two values

Oleksiy Khilkevich oleksiy.khilkevich at gmail.com
Tue Sep 6 06:13:33 EDT 2011

Hi Concurrency Champs

I'm implementing non-blocking cyclic counter mostly for learning purposes,
and faced the following problem, which i'm not sure how to solve.

The method in question implements the following

     * Sets counter value to initial (boundary) value
     * @return true if counter value was changed
    boolean reset();

The implementation I'm not sure about

    public boolean reset() {
        for (;;) {
            int curValue = value.get();
            int curBoundary = boundary.get();
            if (curValue == curBoundary) return false;

            // TODO: if boundary and value were not changed, set the value
to boundary

            return true;

Here I have two values which are both AtomicIntegers and which may change -
value can be incremented or decremented by another thread, and boundary can
be changed too.

I'm not quite sure how to do this without introducing critical sections. In
general the question refers to any shared state change based on values of
several other shared states.

What is the correct way to implement such operation atomically without
critical sections? IS it possible to build composite CAS operations based on
AtomicInteger#compareAndSet ?

Thank you and kindly waiting for your ideas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20110906/592eafae/attachment.html>

More information about the Concurrency-interest mailing list