Search code examples
javamultithreadingatomicjava-5

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?


Solution

  • 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.