Thread Synchronization using Synchronized Block in Java : Free Java Tutorials

Synchronized Block is an alternate way to perform thread synchronization in Java. It reduces unnecessary overhead as it makes only a portion of a method synchronized instead of making the entire method synchronized.

If only a few lines of the code require synchronization, then it is not feasible to declare an entire method as synchronized because unnecessary synchronization will increase overhead.

Instead, we can enclose those few lines of the code by using the synchronized block.

The main advantage of the synchronized block over synchronized method is that it reduces waiting time of threads and improves the overall performance of the system.

We can make a synchronized block in following three different ways:

  1. To get lock of current object: synchronized(this) – If a thread has lock of current object, then only JVM will allow that thread to execute this block.
  1. Obtain lock of particular object: synchronized(object-name) – If a thread has lock of particular object, then only JVM will allow that thread to execute this block.
  1. Get a class level lock: synchronized(Class-name.class) – If a thread has class level lock of class named ‘Class-name’, then only it is allowed to execute this block.

Lock concept is applicable to object types and class types but not to primitives. Hence, we cannot pass primitives as an argument to synchronized block. Otherwise, we will get compile time error (Unexpected Type).

Example of Thread Synchronization using Synchronized Blocks 

class MyThread extends Thread 
{	
	Birthday obj;
	String name;

	MyThread(Birthday obj, String name)
	{
		this.obj = obj;
		this.name = name;
	}
	
	public void run()
	{
		obj.wishBirthday(name);
	}
	
}

class Birthday 
{	
	public void wishBirthday(String name)
	{
		;;;;// Suppose there are thousands of lines of code  
		synchronized(this)
		{
			for(int i=1;i<=5;i++)
			{
				System.out.print("Happy Birthday, ");
				try
				{
					Thread.sleep(2000);
				}
				catch(InterruptedException exp)
				{
					System.out.println("Thread has been interrupted");
				}
				System.out.println(name);
			}
		}
		;;;;// Suppose there are thousands of lines of code 
	}
}

// Main class
public class Demo
{
	public static void main(String args[])
	{
		Birthday obj = new Birthday();
		
		MyThread thread1 = new MyThread(obj, "Meet");
		MyThread thread2 = new MyThread(obj, "Preet");
		
		thread1.start();
		thread2.start();
	}
}

In the above code, assume that wishBirthday() method has thousands of line of code.

In this method only the for-loop portion needs synchronization. So, we have put that loop into a synchronized block in order to reduce unnecessary synchronization.

Since we have done synchronization, the output will be in an organized manner.

Only one thread will execute synchronized block at a time.

Output:

Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Meet

In this case, there was only one object of Birthday class and hence we have used a synchronized block on the current object.

Look at the following example which has two objects of Birthday class.

This example uses synchronized block and gets the class level lock on the Birthday class.

class MyThread extends Thread 
{	
	Birthday obj;
	String name;

	MyThread(Birthday obj, String name)
	{
		this.obj = obj;
		this.name = name;
	}
	
	public void run()
	{
		obj.wishBirthday(name);
	}	
}

class Birthday 
{	
	public void wishBirthday(String name)
	{
		;;;;// Suppose there are thousands of lines of code  
		synchronized(Birthday.class)
		{
			for(int i=1;i<=5;i++)
			{
				System.out.print("Happy Birthday, ");
				try
				{
					Thread.sleep(2000);
				}
				catch(InterruptedException exp)
				{
					System.out.println("Thread has been interrupted");
				}
				System.out.println(name);
			}
		}
		;;;;// Suppose there are thousands of lines of code 
	}
}

// Main class
public class Demo
{
	public static void main(String args[])
	{
		Birthday obj1 = new Birthday();
		Birthday obj2 = new Birthday();
		
		MyThread thread1 = new MyThread(obj1, "Meet");
		MyThread thread2 = new MyThread(obj2, "Preet");
		
		thread1.start();
		thread2.start();
	}
}

Below is the regular output that you will get when you run the above code.

Output:

Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Meet
Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Preet
Happy Birthday, Preet

This is all about Synchronized Blocks in java for thread synchronization. Hope you find this tutorial helpful.

Leave a Comment

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