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?
views:
166answers:
2
+4
A:
My naive implementation would be this:
boolean v;
do {
v=atomicBoolean.get();
} while(!atomicBoolean.compareAndSet(v, !v);
Joachim Sauer
2009-08-10 15:40:54
Beats having to synchronize :)
pjp
2009-08-10 15:44:26
No, it doesn't because the toggle isn't atomic. The value of the AtomicBoolean can change between calling get() and calling compareAndSet()
skaffman
2009-08-10 15:47:14
@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
2009-08-10 15:49:14
sorry, I forgot a "!"
Joachim Sauer
2009-08-10 15:50:00
This is essentially similar to how AtomicInteger incrementAndGet works. for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return next; }
pjp
2009-08-10 16:09:22
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
2009-08-10 20:39:42