Are these two equivalent? In other words, are the ++ and -- operators atomic?
int i = 0;
return ++i;
AtomicInteger ai = new AtomicInteger(0);
return ai.incrementAndGet();
AtomicInteger class provides operations on underlying int value that can be read and written atomically, and also contains advanced atomic operations. AtomicInteger supports atomic operations on underlying int variable. It have get and set methods that work like reads and writes on volatile variables.
It's also possible to achieve thread-safety using the set of atomic classes that Java provides, including AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization.
incrementAndGet() – Atomically increments the current value by 1 and returns new value after the increment. It is equivalent to ++i operation. getAndIncrement() – Atomically increment the current value and returns old value. It is equivalent to i++ operation.
No, ++i
is actually three instructions (load i
, increment, store in i
). It's most definitely not atomic.
The ++ operation are not atomic in java, because it is composed of three operations
So definitively something bad can happen in between
In the case of long, it is even trickier because even the read operation itself is not atomic.
I found a nice article that talks about the memory model
http://www.vogella.de/articles/JavaConcurrency/article.html#memorymodel_atomic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With