gautam
gautam

Reputation: 197

Compare and swap

Is there any way to use CAS operations on more than 1 memory location in Java?

I am attempting to do three CAS operations one by one, but this has a problem of accessing 1st memory location (here old1) by a thread while next memory location (here old2) being compared by another thread. For instance,

if(CAS(old1,exp1,new1))

    if(CAS(old2,exp2,new2))

    if(CAS(old3,exp3,new3))

Is it possible to do something like:

CAS(old1,old2,old3,exp1,exp2,exp3,new1,new2,new3)  ??

Upvotes: 1

Views: 1258

Answers (2)

Alexey Malev
Alexey Malev

Reputation: 6533

If you want three cas operations together form an atomic operation, I think you need synchronized block/method.

You may also consider creating a wrapper class with three fields and doing CAS on reference:

public class ThreeValueHolder {
    private final int value0, value1, value2;

    public ThreeValueHolder(int value0, int value1, int value2) {
        this.value0 = value0;
        this.value1 = value1;
        this.value2 = value2;
    }

    //getters
}

And then use this class together with AtomicReference:

public volatile AtomicReference<ThreeValueHolder> ref = null;

...

ref.compareAndSet(current, new ThreeValueHolder(1, 2, 3));

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198033

Put all three fields into one immutable object, a Foo. Then, given an AtomicReference<Foo> ref, write:

Foo current = ref.get();
if (foo.val1() == exp1 && foo.val2() == exp2 && foo.val3() == exp3) {
  return ref.compareAndSet(current, new Foo(new1, new2, new3));
} else {
  return false;
}

Upvotes: 3

Related Questions