Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java int concurrency ++int equivalent to AtomicInteger.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();
like image 249
Finbarr Avatar asked May 05 '10 07:05

Finbarr


People also ask

Why do we use AtomicInteger?

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.

Is AtomicInteger thread safe?

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.

How do you increment an atomic integer?

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.


2 Answers

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

like image 194
gustafc Avatar answered Nov 02 '22 21:11

gustafc


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

like image 35
Mario Ortegón Avatar answered Nov 02 '22 23:11

Mario Ortegón