Search code examples
javamultithreadingstaticjava-threads

Does this code have a race condition?


I just need to do an example of race condition with java threads, I writed this code, but I'm not sure if it has a race condition.

Can someone tell me if the below code has a race condition,and also how can I improve it or make it simple?

(sorry for bad english)

public class RaceCondition extends Thread{

static int count=0;   //the variable where the race condition need to happen
static int contador1 = 0;    //variables to count
static int contador2 = 0;


static Thread t1 = new Thread(new Runnable() {
    public void run(){

        while(contador1!=20){
        count ++;
        System.out.print(count + " ");
        contador1++;

        }
    }
     });

static Thread t2 = new Thread(new Runnable() {
    public void run(){
        while(contador2!=20){

        int k = 5;
        count += 5*k;
        System.out.print(count + " ");
        contador2 ++;

        }
    }
     });

public static void main(String[] args) {

     t1.start();
     System.out.println(" ");
     t2.start();

    }

}   

Solution

  • You do have a race condition. Neither of the ++ or += operations is implemented as an atomic operation in Java, the two threads can interfere with each other when they're both trying to read and update the count field.

    Also there is no guarantee that updates to the shared variable will be visible across threads so one thread might not even see the other thread's updated value.

    You can fix both problems by making the count static variable an AtomicInteger. Use getAndIncrement instead of ++, and getAndAdd instead of +=.

    For why ++ works like this, see Why ++ is not implemented as an atomic operation in Java.