Thread Synchronization and Locking Mechanism in Java : Free Java Tutorials

Thread Synchronization is done in Java using the synchronized keyword which uses locking mechanism to synchronize threads in a multi-threaded environment. Synchronized is the modifier applicable to methods and blocks. It is not applicable to variables and classes.

If multiple threads are trying to operate on the same java object simultaneously, then there is a chance of data inconsistency problem.

Take the example of IRCTC (Indian Railway Catering and Tourism Corporation) to understand data inconsistency problem. Thousands of customers book tickets online throughout the day. Consider a scenario where there are only 10 tickets left and two customers are simultaneously trying to book 7 tickets. Since there are only 10 tickets, this can lead to data inconsistency problem.

To overcome this data inconsistency problem, we should use synchronized keyword. If a method or block is declared as synchronized, then at a time only one thread is allowed to execute that method or block on the given object. So that data inconsistency problem is resolved.

There is also one disadvantage of using synchronized keyword. It increases waiting time of threads and creates performance overhead. Hence, if there is no specific requirement, then it is not recommended to use synchronized keyword.

Thread Synchronization concept is implemented internally by using locking mechanism. Every object in Java possesses a unique lock. Whenever we are using the synchronized keyword, lock concept will come into the picture.

If a thread wants to execute synchronized method on the given object, first it has to get the lock of that object. Once the thread has got the lock, then it is allowed to execute any synchronized method on that object.

Once method execution completes, automatically thread releases lock and then only other thread can get that lock and execute that synchronized method. JVM internally takes care of acquiring and releasing the lock and programmer is not responsible for this.

While a thread is executing synchronized method on a given object, the remaining threads are not allowed to execute any synchronized method simultaneously on the same object. But remaining thread can execute non-synchronized methods simultaneously.

Example of Thread Synchronization 

class MyThread1 extends Thread 
{	
	public void run()
	{
		// calling static method-1 from thread1
		MyClass.method1();
	}
}

class MyThread2 extends Thread 
{	
	public void run()
	{
		// calling static method-2 from thread2
		MyClass.method2();
	}
}

class MyThread3 extends Thread 
{	
	public void run()
	{
		// calling static method-3 from thread3
		MyClass.method3();
	}
}


// We create our own class named MyClass
class MyClass 
{	
	public static synchronized void method1()
	{
		System.out.println("Method-1 is under execution");
		try
		{
			// sleeping for 5 seconds
			System.out.println("Method-1 is sleeping for 5 seconds");
			Thread.sleep(5000);
			System.out.println("Method-1 has finished execution");
		}
		catch(InterruptedException exp)
		{
			System.out.println("Thread has been interrupted");
		}
	}
	
	public static synchronized void method2()
	{
		System.out.println("Method-2 is executing");		
	}
	
	public static void method3()
	{
		System.out.println("Method-3 is executing");
	}
}

// Main class
public class Demo
{
	public static void main(String args[])
	{
		// Creating and starting three threads to call 3 static methods of MyClass
		MyThread1 thread1 = new MyThread1();
		MyThread2 thread2 = new MyThread2();
		MyThread3 thread3 = new MyThread3();
		
		thread1.start();
		thread2.start();
		thread3.start();
	}
}

In the above program, there are two synchronized methods in the class named MyClass. Three threads have been started simultaneously to invoke three static methods of MyClass.

When thread1 first starts its execution and calls synchronized method1(), thread1 has the lock for the static object of MyClass. Now, method1 goes into the sleep state for 5 seconds. During this time, thread2 calls synchronized method2().

Since synchronized method1() has the lock, thread2 cannot execute method2 until method1 finishes its execution. You can see from the output that method2 will execute only after  method1 completes its execution and releases lock.

However, when method1 is in the sleep state for 5 seconds, thread3 can call method3 because that method is not synchronized and so JVM will not ask for the lock from that method. So method3 will finish its execution during those 5 seconds. Method2 will execute only after those 5 seconds.

Look at the output below for better understanding.

Output:

Method-1 is under execution
Method-1 is sleeping for 5 seconds
Method-3 is executing
Method-1 has finished execution
Method-2 is executing

This is all about thread synchronization and locking mechanism in Java. Hope you find this tutorial helpful.

Leave a Comment

Your email address will not be published. Required fields are marked *