Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...