Using compare and set against multiple expected values with AtomicReference

910 Views Asked by At

I have a bit of a unique situation. I'd like to be able to use the compareAndSet() feature of AtomicReference but with a bit of a twist.

Normally you use compareAndSet() to compare against a single, expected value before you actually change it. In my case the expected value to compare against could be one of many values.

Is there a way to do this using AtomicReference? If not, what other techniques should I use? Perhaps just traditional use of synchronized?

1

There are 1 best solutions below

1
On

I'm going to assume that you have a Set of expected values. In that case...

<T> boolean setIfInExpected(AtomicReference<T> ref, Set<?> expected, T newValue) {
  while (true) {
    T current = ref.get();
    if (set.contains(current)) {
      if (atomicReference.compareAndSet(current, newValue)) {
        return true;
      }
    } else {
      return false;
    }
  }
}

This is typical for how uses of compareAndSet work: they run in a loop until the AtomicReference doesn't change between the get and the compareAndSet.