by BehindJava

What is Race Condition In MultiThreading Java

Home » java » What is Race Condition In MultiThreading Java

In this tutorial we are going to learn about Race Condition in MultiThreading Java and its resolution.

Race Condition
When two or more threads try to update the mutually shared resource(data) at the same time, Race condition occurs.

Example:
The expected result of the below program is 10 when we run it for the first time. But the counter value keeps on changing when we execute the same program again and again which creates data inconsistency because two threads accessing the same counter value and tries to update the same counter value.

public class RaceCondition implements Runnable {

	private int counter;

	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			try {
				Thread.sleep(1000);
                counter++;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public int getCounter() {
		return counter;
	}

	public static void main(String args[]) {

		RaceCondition rc = new RaceCondition();

		Thread t1 = new Thread(rc);
		t1.start();

		Thread t2 = new Thread(rc);
		t2.start();

		try {
			t1.join();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			t2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Counter value:" + rc.getCounter());

	}
}

Try executing rhe program and see the inconsistent output upon executing the same code multiple times. Here is the solution for this problem i.e., Synchronized