| Author |
Race Condition
|
Manjunatha Kampli Kottal
Greenhorn
Joined: Apr 20, 2010
Posts: 6
|
|
|
Can anybody explain when the race condition occurs? is it because of the way thread scheduling works or because of the bad programming? i think its because of thread scheduling mechanism but not sure.please clarify
|
 |
Prabakar Kalivaradan
Greenhorn
Joined: Dec 12, 2011
Posts: 20
|
|
>Race Condition: The possibility of incorrect results in the presence of unlucky timing; the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime; in other words, getting the correct result depends on chance factor;
>The most common type of race condition is check-then-act, where a potentially stale observation is used to make a decision on what to do next
1. if(obj == null)
2. obj = new OnlyOne();
In the above example, say you don't want to create more than one OnlyOne() object; if thread A comes to line 1 then moves to line 2 because obj is null; at the same time if thread B enters line 1 before thread A creates OnlyOne(), thread B also will see that obj is null; so both will end up creating their own OnlyOne objects; so there are two objects now which you didn't want.
This is called race condition.
|
-prabak
|
 |
Prabakar Kalivaradan
Greenhorn
Joined: Dec 12, 2011
Posts: 20
|
|
|
Basically Race condition occurs due to poor design (concurrent design).
|
 |
Manjunatha Kampli Kottal
Greenhorn
Joined: Apr 20, 2010
Posts: 6
|
|
@Prabakar Kalivaradan
Thanks for the example. so you mean to say race condition is because of the poor design. and by properly synchronizing the code we can avoid the race condition right?
just like
synchronized(this)
{
if(obj == null)
obj = new OnlyOne();
}
|
 |
Prabakar Kalivaradan
Greenhorn
Joined: Dec 12, 2011
Posts: 20
|
|
right!
with the right design and implementation that follows that right design such conditions can be avoided.
it becomes harder to rectify after the implementation.
|
 |
 |
|
|
subject: Race Condition
|
|
|