Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Race conditions "check-then-act" and "read-modify-write"

Anyone can explain me about what is race condition, how to avoid it, and how to find it out in java codes?

Okay, I just know "race condition" several days, I have two examples, maybe they are not good enough, that's why I need your help:) Hope any of you can explain it for me.

example1: check then act:

if(vector.contains(e))//check
{
vector.remove(e)
}

if there are 2 threads can access, thread1 suspends after check vector contains e, and e does in vector, then thread2 access to check and then remove e from vector, then thread1 comes back and do remove action, error will occur, because e is already removed by thread2.

example2: read modify write:

assume we have a counter variable in a method, once the method is called, counter increase 1,

counter++

this is not a atomic operation, it has 3 steps: 1. get the value 2. increase the value 3. assign to the value

What I know about race condition is all here, hope you can share your knowledge with me:)

thanks

like image 796
Haifeng Zhang Avatar asked Oct 24 '12 14:10

Haifeng Zhang


1 Answers

What is a race condition? Check this stack-overflow question.

There are primarily two scenarios for race-condition: read-modify-write and check-then-act.

For read-modify-write classical example is of counter++ which is not an atomic operation so leads to race condition.

For check-then-act there are multiple examples. One example is when you check for key existence in ConcurrentHashMap and then do some work in if-case. Another example is singleton class code:

public Singleton getInstance()
{
   if(_instance == null)
   { 
      _instance = new Singleton();
   }
}

You can read more about them on internet. One good book on concurrency is Java Concurrency in Practice by Brian Goetz. You can also find this article helpful.

like image 156
akhil_mittal Avatar answered Nov 14 '22 23:11

akhil_mittal