If two threads both increment same int i
using i++, we could get a problem, as i++ is not atomic operation. That is why there is AtomicInteger.increment()
, which makes incrementing atomic. So if we had 1 core and 2 threads doing .increment()
, there could be absolutely no problem (as it can't be suspended in the middle of operation).
But what if we had 2 cores and 2 threads and they parallelly (at exactly the same time) call that increment()
?
Could there be possibility that they load same value of int i
? Meaning if int i
was 1, end result would be 2 and not 3. In that case we don't care if it is atomic operation as they both took same value at the same time..
Bottom line: is synchronization handled by AtomicInteger?