Reputation: 1813
Would this operation be atomic or is there a chance of data race in between?
atomicInteger.set(-atomicInteger.get());
If there is a data race, how to negate an AtomicInteger
atomically?
Upvotes: 0
Views: 176
Reputation: 135992
I would do it this way
public int getAndNegate(AtomicInteger i) {
for (;;) {
int current = i.get();
int next = -current;
if (i.compareAndSet(current, next))
return current;
}
}
Upvotes: 3
Reputation: 26094
public final int getAndDecrement()
Atomically decrements by one the current value. Returns the previous value
AtomicInteger itsCounter = new AtomicInteger();
itsCounter.getAndDecrement();
Upvotes: 0
Reputation: 31648
No you need to synchronize to lock the instance I guess.
AtomicInteger has lots of methods to getAndSet but nothing to do inverse...
Apparently this was asked before on SO Does AtomicBoolean not have a negate() method? The solution on that page is interesting.
Upvotes: 1