[concurrency-interest] Suggestion: .hardGet() for atomic variables

Raph Frank raphfrk at gmail.com
Thu Jan 19 12:53:18 EST 2012


In my thread "Volatile happens before question", one of the issues
with the .get() method is that it only counts as a volatile read.
This means that if you read the old value of the variable, it doesn't
establish any happens-before relationship.

A .hardGet() would be a get that also counts as a volatile write.

This would mean that if you .hardGet() on an atomic variable, it would
happen-before the write that over-writes the value that was read (at
least assuming that write was a combined read/write operation).

I assume that atomicInteger.getAndAdd(0) is equivalent?

Can atomicInteger.getAndAdd(0) be optimized away, or would it be
guaranteed to count as both a volatile read and write?

So, if a sequence counter is incremented at the start and end of all
write operation, then something like this would allow a read attempt.

final SomeType value = new SomeType();

boolean tryWrite(int value) {
  synchronized(this) {
    sequence.incrementAndGet();
    this.value.setInt(value);
    sequence.incrementAndGet();
  }
}

int tryRead() {
  int sequence = counter.get();

  int value = this.value.getInt();

  if (isEven(sequence) && sequence == counter.hardGet()) {
    return value;
  } else {
    return -1;
   }
}

(This assumes that calling .get() on SomeType won't explode if the
data is written to at the same time)


More information about the Concurrency-interest mailing list