javaatomicatomicinteger

Does AtomicInteger handle synchronization?


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?


Solution

  • Could there be possibility that they load same value of int i?

    Yes, there is, but it's handled for you.

    The incrementAndGet method uses an atomic "compare and set" operation that sets the incremented value but only if a new value was not already set. If the compare fails, incrementAndGet fetches the new value and tries again.

    The net effect is, it is safe to use incrementAndGet from multiple threads.