Race conditions

We talk about race conditions when the result of a calculation may be different based on the speed and CPU access of the different parallel running threads. Let's take a look at the following two methods:

   void method1(){
1       a = b; 
2       b = a+1; 
        } 
    void method2(){ 
3       c = b; 
4       b = c+2; 
        }

The order of the lines can be 1234, 1324, 1342, 3412, 3142, or 3142. Any execution order of the four lines may happen that assures that 1 runs before 2 and 3 runs before 4, but there are no other restrictions. Assuming that the value of b is zero at the start, the value of b, is either 1 or at the end of the execution of the segments. This is almost never what we want. We prefer it if the behavior of our program is not stochastic except, perhaps ...

Get Java Projects - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.