Java int concurrency ++int equivalent to AtomicInteger.incrementAndGet()?
Are these two equivalent? In other words, are the ++ 开发者_JS百科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
- Read the value stored (atomic)
- Adds one to it (atomic)
- Store value (atomic)
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
精彩评论