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
>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.
Basically Race condition occurs due to poor design (concurrent design).
Manjunatha Kampli Kottal
Joined: Apr 20, 2010
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?
if(obj == null)
obj = new OnlyOne();