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();
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();
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