mindreader
mindreader

Reputation: 1813

Are nested method calls of AtomicInteger also atomic in java

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

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

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

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

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

dkatzel
dkatzel

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

Related Questions