No. The statement i++ is not an Atomic operation. It has more than
one operation.
First JVM loads the current value of i in memory. Then it
increments it. Finally it stores the new value back into variable i.
The current thread that executes this operation may be interrupted
between any of the above-mentioned three steps. Therefore it is not
an atomic operation
xxxxxxxxxx
public class SafeCounterWithoutLock {
private final AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
}
public void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
}
}