Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is iinc atomic in Java?

Tags:

java

atomic

jvm

I know increment operation is not atomic in C++ without locking.

Will JVM add any lock on its implementation of iinc instruction?

like image 565
StarPinkER Avatar asked Mar 08 '13 05:03

StarPinkER


1 Answers

No its not

  • Retrieve the current value of c.
  • Increment the retrieved value by 1.
  • Store the incremented value back in c.

Java Documentation for Atomicity and Thread Interference

You need to either use synchronized keyword or use AtomicXXX methods for Thread safety.

UPDATE:

public synchronized void increment() {
    c++;
}

or

AtomicInteger integer = new AtomicInteger(1);
//somewhere else in code
integer.incrementAndGet();

Also read: Is iinc atomic in Java?

like image 132
Narendra Pathai Avatar answered Nov 07 '22 00:11

Narendra Pathai