Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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;
    }
}
public final int getAndDecrement()

Atomically decrements by one the current value. Returns the previous value

AtomicInteger itsCounter = new AtomicInteger();
itsCounter.getAndDecrement();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top