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

Kasper Nielsen kasper at kav.dk
Tue Sep 6 08:28:32 EDT 2011


Since you are using to ints.
You might just go with an AtomicLong and mask the values.

(high 32 bits = value, low 32 bits = boundary)

cheers
   Kasper


On 06-09-2011 12:13, Oleksiy Khilkevich wrote:
> 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
>
>      @Override
>      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
> Oleksiy
>
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest



More information about the Concurrency-interest mailing list