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

Vitaly Davidovich vitalyd at gmail.com
Thu Jan 19 13:07:41 EST 2012


A volatile read gives you current value in memory (coherent cache).  This
volatile read happens before any subsequent operations (read or write),
volatile or not.  Why is this not good enough for you?

Sent from my phone
On Jan 19, 2012 12:55 PM, "Raph Frank" <raphfrk at gmail.com> wrote:

> 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)
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120119/2f108aab/attachment.html>


More information about the Concurrency-interest mailing list