I was reading some documents about Atomic variables in Java. As written everywhere, AtomicInteger is supposed to be thread-safe.
As per my understanding of atomic integers, it works on the principle of Compare and Swap algorithm. I am unable to understand how will this work in case, when two threads try to increment the same atomic variable a exactly same time.
say I have define AtomicInteger var = 1
, and this is being used by two threads Thread_1
and Thread_2
. What will happen when both the thread will try to increment the var
at the same time T1
.
I know this will be rare situation, but what if it happens. In compare and swap, it reads and updates the variable in a single atomic operation and it checks value from memory. so what if at time T1-1
, value of var is 5 and both Thread1
and Thread2
will start incrementing it?
Which one will fail? Will it be random behaviour? or I am missing something very basic.