0

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()?

Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • I believe spec wise the cAS call can continue to fail as the `getOpaque()` call returns the 'wrong' value for millions of loops, in theory. I would go with trying this operation just once, and if it fails, do the loop you pasted, but with `getVolatile` instead of `getOpaque`. – rzwitserloot May 22 '23 at 21:36
  • This belongs on https://codereview.stackexchange.com/ – Jim Garrison May 23 '23 at 00:24

0 Answers0