Friday, 22 April 2016

What is the Race condition and its side effects in concurrency ?


Example
public class Unsafe {
   private int counter;

   public int increment() {
      return counter++;
   }
}

When above code is called by multiple threads for Read>Modify>Write operation, one can access or modify the variables that other threads might be using.

Thread 1.   counter=5  ----------> 5++ = 6 --------->  counter=6
Thread 2.   --------> counter=5 --------> 5++ = 6 --------->  counter=6

This concurrency problem called a RACE CONDITION.
The race condition requires a perfect timing and can lead to the serious side effects.

Solution
public class Safe {
   private int counter;

   public synchronized int increment() {
      return counter++;
   }
}


Side effects of race condition could be :
  1. Unreliable or incorrect result
  2. Serious Data integrity problem
  3. Getting right answer relies on lucky timing


Race condition don't always result in failure , Some unlucky timing is also required.


AVOIDING RACE CONDITION
To avoid race conditions, prevent other threads from using a variable while a thread is in middle of modifying it.
Ensure that other threads can modify the state only before one start or after finish, but not in the middle.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.