开发者

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

  1. Read the value stored (atomic)
  2. Adds one to it (atomic)
  3. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜