Race Condition

Race Condition

A race condition occurs when two or more threads can access shared data and they try to change it at the same time.

Problem: When one thread is in check and act then other thread might change the value in between **check and act **resulting unusual result.

public synchronized lockResource(){
if (a == 10) // "Check" state
{
b = a * 2; // "Act" state
}
}

If another thread changed a in between check and act b will not be equal to 20.

In order to prevent race conditions from occurring, we put a lock around the shared resource/data to ensure only one thread can access the data at a time.

public synchronized lockResource(){
if (a == 10)
{
b = a * 2;
}
}
//releases lock here