javajvmatomic

Is iinc atomic in Java?


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

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


Solution

  • No its not

    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?