Have I implemented an atomic circular counter correctly using VarHandles

68 Views Asked by At

My code:

static final VarHandle COUNTER_VAR_HANDLE = //;
static final int MAX = 10;

int counter = -1;

int getNext() {
  var next = 0;
  var prev = 0;

  do {
    prev = (int) COUNTER_VAR_HANDLE.getOpaque(this);
    next = (prev + 1) % MAX;
  } while (!COUNTER_VAR_HANDLE.compareAndSet(this, prev, next));

  return next;
}

Trying to understand VarHandles and their different uses. Given a recent architecture (e.g. x86), is this the correct implementation of a getNext() method?

If my reading serves me correctly there is no benefit to using weakCompareAndSet on a modern achitecture but I wasn't sure whether I needed getVolatile() instead of getOpaque() in this circumstance. Am I going to run into issues with multiple threads calling getNext()?

0

There are 0 best solutions below