Race Conditions & Data Races: What And How To Prevent

Deepak Singh
3 min readApr 26, 2020

Holy Crap, what’s that my service got crashed…. I spent days in learning this, I don’t want you to get stuck with this :-)

While working with multiple threads we are most likely to encounter these two.

Race Condition and Data Race

Let’s start with Race Condition:

This condition occurs when multiple threads are accessing a shared resource and at least one thread is modifying the resource. The timing of thread’s scheduling may cause incorrect results. The core of the problem is the execution of non-atomic operations performed on the shared resource.

For Example

Two Threads are executing two operations on a shared resource called items. There is a race b/w the last operations b/w the incrementing thread and decrementing thread. If the decrementing thread is scheduled before the incrementing thread the result is 1.

but if the decrementing thread is scheduled after the incrementing thread the result is -1.

--

--

Deepak Singh
Deepak Singh

No responses yet