views:

221

answers:

2

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();
+7  A: 

No, ++i is actually three instructions (load i, increment, store in i). It's most definitely not atomic.

gustafc
That's what I thought. Read value, increment value, get value.
Finbarr
And it is not even atomic if `i` is declared as `volatile`.
Stephen C
+2  A: 

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

Mario Ortegón