views:

166

answers:

2

Does java.util.concurrent.atomic.AtomicBoolean not have a method that can atomically negate/invert the value? Can I do it another way? Am I missing something?

+4  A: 

My naive implementation would be this:

boolean v;
do {
  v=atomicBoolean.get();
} while(!atomicBoolean.compareAndSet(v, !v);
Joachim Sauer
Beats having to synchronize :)
pjp
No, it doesn't because the toggle isn't atomic. The value of the AtomicBoolean can change between calling get() and calling compareAndSet()
skaffman
@skaffman: in which case the compareAndSet() will fail, return false and the loop will be re-entered. Correct me if I got anything wrong.
Joachim Sauer
sorry, I forgot a "!"
Joachim Sauer
This is essentially similar to how AtomicInteger incrementAndGet works. for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return next; }
pjp
A: 

In my opinion, AtomicBoolean is rarely useful. In essence, it's an AtomicInteger which wraps at 1. So you either get 0 or 1, does it really matter if the negate operation is atomic?

For the boolean value to be meaningful, you must have some atomic action associated with the changing of the value, like flipping the disabled status of a button, counting how many times it's flipped etc. You can't associate any action with an atomic negate operation, you will need mutex or binary semaphore to protect the negation operation and action together.

ZZ Coder