Concurrency in Android: Race condition

In this part, we investigate one of the multi-threading or concurrency issues. A common example of a correctness problem occurs when two threads need to modify the value of the same variable based on its current value. Let’s consider that we have a myInt integer variable with the current value of 2.

In order to increment myInt, we first need to read its current value and then add 1 to it. In a single-threaded world, the two increments would happen in a strict sequence—we will read the initial value 2, add 1 to it, set the new value back to the variable, and then repeat the sequence. After the two increments, myInt holds the value 4.

Continue reading…