Synchronization in java

In this post, we will learn synchronization in java, and why we need Java synchronization, how to write synchronized code and more important points about synchronization.

Here is the table content of the article will we will cover this topic.
1. Synchronization in java?
2. Why use Synchronization in Java?
3. Locks in Java?
4. Types of Synchronization?
5. Multi-threading without Synchronization?
6. Multi-threading with Synchronization?
7. Important points about java synchronized?

8. Java synchronized block
i) synchronized block in non-static method
ii) synchronized block in static method

9. Java synchronized method
i) Java synchronization with non-static method
ii) Java synchronized method

Synchronization in java

In a multithreading environment, multiple threads can try to access the same resources and can produce erroneous and unforeseen results. Java provides a way to control the access of multiple threads to any shared resource. Synchronization in java is a process where we want to allow only one thread to access the shared resource at a time. So that multiple threads can work together without creating any problem. The synchronization process can achieve by synchronized keyword in java. The Synchronization keyword makes the code thread safe.

Synchronization in java

Why use Synchronization in Java?

Suppose you have two threads inside a program. There may be a chance when multiple threads try to attempt the same resource and produce errors. So synchronization is used to handle the following errors:

1. Thread Interference Error: The thread interference error occurs when we have more than one thread and they are running simultaneously.  Because they want to access the same piece of data and perform different operations on the same data. The operation of one thread could overlap by other thread and leads to data inconsistent.

2. Memory Consistency Error: The memory Consistency Error occurs when the changes made by one thread may not be visible to the other threads. The other threads have inconsistent views of the same shared data.

Locks in Java

Before moving further in synchronization, we have to understand the concept of lock or monitor. In java, Each and every object has a lock associated with it. When multiple threads access the shared resource, they use the lock. A thread request for a lock to an object and access data from object meanwhile all other thread wait to release the lock. A thread releases the lock after completion of work.

Types of Synchronization

There are 2 types of synchronization in java as shown below:

1. Process Synchronization: The simultaneous execution of multiple threads or processes to reach a state such that they commit to a certain sequence of actions.

2. Thread Synchronization: Thread Synchronization allows to access the shared space only one thread at a time.

In this post, we will discuss the thread synchronization. The thread synchronization is divided in two parts.

1. Mutual Exclusive:  A mutual exclusion is the simplest type of thread synchronization. This synchronization allows only one thread can execute the shared resource at a time.When thread accesses the shared resource, it takes a lock and all other threads wait to release the lock.  Let’s read how we can achieve it. There are two ways
1. Synchronized method.
2. Synchronized block.

2. Cooperation (Inter-thread communication in java): Interthread communication in java is used to avoid polling and important when you want to develop an application where two or more threads exchange some information. Java provides three methods which are used to inter thread communication. Those methods are wait(), notify() and notifyAll() and these methods belong to object class.

Multi-threading without Synchronization

Let’s discuss an example which prints the count by two different threads.

class Count
{  
	void printTable(int n)
	{
		//method not synchronized  
	   for(int i=1;i<=5;i++)
	   {  
	     System.out.println(n*i);  
	     try
	     {  
	       Thread.sleep(400);  
	     }
	     catch(Exception e){System.out.println(e);}  
	   }  
	  
	 }  
}  
  
class MyThread1 extends Thread
{  
	Count c;  
	MyThread1(Count c)
	{  
		this.c=c;  
	}  
	public void run()
	{  
		c.printTable(5);  
	}  
	  
}  
class MyThread2 extends Thread
{  
	Count c;  
	MyThread2(Count c)
	{  
		this.c=c;  
	}  
	public void run()
	{  
		c.printTable(100);  
	}  
}  
  
public class WithoutSynchronization
{  
	public static void main(String args[])
	{  
		Count obj = new Count();//only one object  
		MyThread1 t1=new MyThread1(obj);  
		MyThread2 t2=new MyThread2(obj);  
		t1.start();  
		t2.start();  
	}  
}  

Output: 5
100
200
10
15
300
400
20
500
25

Multi-threading with Synchronization

class Count
{  
	synchronized void printTable(int n)
	{
		//method not synchronized  
	   for(int i=1;i<=5;i++)
	   {  
	     System.out.println(n*i);  
	     try
	     {  
	       Thread.sleep(400);  
	     }
	     catch(Exception e){System.out.println(e);}  
	   }  
	  
	 }  
}  
  
class MyThread1 extends Thread
{  
	Count c;  
	MyThread1(Count c)
	{  
		this.c=c;  
	}  
	public void run()
	{  
		c.printTable(5);  
	}  
	  
}  
class MyThread2 extends Thread
{  
	Count c;  
	MyThread2(Count c)
	{  
		this.c=c;  
	}  
	public void run()
	{  
		c.printTable(100);  
	}  
}  
  
public class WithSynchronization
{  
	public static void main(String args[])
	{  
		Count obj = new Count();//only one object  
		MyThread1 t1=new MyThread1(obj);  
		MyThread2 t2=new MyThread2(obj);  
		t1.start();  
		t2.start();  
	}  
}  

Output: 5
10
15
20
25
100
200
300
400
500

Important points about java synchronized

1. Synchronized keyword in Java is used to synchronize the shared resource when multiple threads use it. Synchronization in Java is used to remove the thread interference and memory inconstancy.

2. Java allows us to use the synchronized keyword with method or block.

3. The concept of synchronization works based on lock. Whenever a thread enters into java synchronized method or blocks it acquires a lock and releases the lock after completion of execution.

4. When a thread enters into a non-static synchronized method, it acquires an object level lock . But when the thread enters into static synchronized java method it acquires a class level lock.

5. when a java synchronized method calls another synchronized method then it requires the same lock. But the current thread can enter without a lock because it already holding the lock.

6. Synchronized block throws NullPointerEception, if object used in java synchronized block is null.

7.  A synchronized method slow and can degrade performance because threads have to wait for their turn.

8. It is always better to use the Java synchronized block instead of synchronized method  because the using synchronized block only locks critical section of code and avoid locking the whole method.

9. The static synchronized and non-static synchronized method can run simultaneously because they lock on the different object.

Leave a Comment