by BehindJava

What is Synchronized in Java MultiThreading

Home » java » What is Synchronized in Java MultiThreading

In this tutorial we are going to learn to learn about Synchronized in Java MultiThreading

MultiThreading
The Process of executing two or more threads simultaneously.

To understand the Synchronized keyword better we need to know more about the Race condition.
Example:
We have int x=10 and looping it 10 times incrementing the x each time. In this case lets say we have two threads executing this block of code. When we run the same program multiple times result becomes inconsistent because two threads might be reading the same value and incrementing the x.

int x=10;
for(int i=0;i<10;i++){
    x=x+1;
}
//Read the value of x
//Add 1  to this value
//Store this value back to x

Synchronized

  • Allows only a single thread at a time to access the shared resource, and forces all other threads to wait for that accessing thread to release its access to the shared resource.
  • Each object in Java has a unique lock.
  • Applied on methods/blocks.
  • Occurs on an object. Only one thread can execute a synchronized method/block at a time for any given single object.
  • Mutual exclusion(Obtaining lock on the shared resource).

Example:
Now the issue is resolved by adding synchronized keyword to the run method which makes the result consistent.
When we use synchronized to the run method t1 object gets the lock to the run method and once its execution is completed, lock is released and t2 obtains the lock on run method.

public class RaceCondition implements Runnable {

	private int counter;

	@Override
	public synchronized void run() {
		for (int i = 0; i < 5; i++) {

			try {
				counter++;
				Thread.sleep(100);
			} 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();
			t2.join();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

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

Output:

Counter value:10