Hi,

I have an atomic counter that gets incremented and decremented over
time (non monotonically).
At a certain point, I would like to enter a termination protocol where
increments are not possible anymore and I set an action to run if/when
the counter reaches zero.
Trivial when using synchronized/lock, but I'd like to give it a try
without them.

class A {
  private final AtomicLong counter;
  // Non-volatile
  private Runnable action;

  void terminate(Runnable action) {
    this.action = action;
    // Volatile write needed here for visibility.
    if (counter.addAndGet(0) == 0) {
      action.run();
    }
  }

  void decrement() {
    // Volatile read required to see this.action.
    if (counter.decrementAndGet() == 0) {
      Runnable a = this.action;
      if (a != null) {
        a.run()
      }
    }
  }
}

Is addAndGet(0) a volatile write? Can the write be optimized away?
Similarly (although not relevant for this particular example), a
_failed_ compareAndSet() has the semantic of a volatile write even if
the set part was not done because the compare part failed?

Thanks!

-- 
Simone Bordet
---
Finally, no matter how good the architecture and design are,
to deliver bug-free software with optimal performance and reliability,
the implementation technique must be flawless.   Victoria Livschitz

-- 
You received this message because you are subscribed to the Google Groups 
"mechanical-sympathy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to mechanical-sympathy+unsubscr...@googlegroups.com.
To view this discussion on the web, visit 
https://groups.google.com/d/msgid/mechanical-sympathy/CAFWmRJ3qGJ_qqrXmAHNDZ6ro01BQwe8czHZP7b-SoZ%2BrULhJAw%40mail.gmail.com.

Reply via email to