Thread Synchronization in Java | We know that multithreading increases the speed of execution of a program and optimize the computer resource usage.
Normally, multiple threads in a single program run asynchronously if threads do not share a common resource.
Under some circumstances, it is possible that more than one thread access the common resource (shared resource). That is, more than one thread access the same object of a class.
In this case, care must be taken by the programmer that only one thread use shared resource at a time. The technique through which the solution to this problem is achieved is called synchronization in Java.
In other words, when a thread is already accessing an instance of a class, preventing any other thread from acting on the same instance is called ‘thread synchronization in Java‘ or ‘ Thread safe‘.
The object on which threads are synchronized is called synchronized object. The synchronization of thread is recommended when multiple threads are accessing the same object. That is, when you are working in multi-threading.
The purpose (objective) of thread synchronization is to control the use to shared resources. Java provides a keyword named “synchronized” that helps to synchronize thread.
Let’s understand better the need of synchronization technique by taking realtime examples.
Realtime Example of Synchronization in Java
1. Suppose a thread in a program is reading a record from a file while another thread is still writing the same file. In this situation, the program may produce undesirable output.
2. Let’s take a scenario of railway reservation system where two passengers are trying to book seats from Dhanbad to Delhi in Rajdhani Express. Both passengers are trying to book tickets from different locations.
Now suppose that both passengers start their reservation process at 11 am and observe that only two seats are available. First passenger books two seats and simultaneously the second passenger books one seat.
Since the available number of seats are only two but booked seats are three. This problem happened due to asynchronous access to the railway reservation system.
In this realtime scenario, both passengers can be considered as threads, and the reservation system can be considered as a single object, which is modified by these two threads asynchronously.
This asynchronous problem is known as race condition in which multiple threads access the same object and modify the state of object inconsistently.
The solution to this problem can be solved by a synchronization mechanism in which when one thread is accessing the state of object, other thread will wait to access the same object at a time until their come turn.
Object Lock in Java
The code in Java program can be synchronized with the help of a lock. A lock has two operations: acquire and release. The process of acquiring and releasing object lock (monitor) of an object is handled by Java runtime system (JVM).
In Java programming language, every object has a default object lock that can be used to lock on a thread. This object lock is also known as monitor that allows only one thread to use the shared resources (objects) at a time.
To acquire an object lock on a thread, we call a method or a block with the synchronized keyword. Before entering a synchronized method or a block, a thread acquires an object lock of the object.
On exiting synchronized method or block, thread releases the object’ monitor lock. A thread can again acquire the object’ monitor lock as many times as it wants.
Object lock is like a room with only one door. A person enters the room and locks the door from inside. The second person who wants to enter the room will wait until the first person come out.
Similarly, a thread also locks the object after entering it, the next thread cannot enter it until the first thread comes out. Since the object is locked mutually on threads, therefore, this object is called mutex (mutually exclusive lock).
Look at the below figure to understand thread synchronization in Java better.
Thus, when a thread acquires a lock associated with an object to access shared resources, other thread waits to acquire lock associated with the object at that time.
Rules for synchronizing shared resources in Java
In the Java program, there must mainly three rules to be followed when synchronizing share resources. The rules are as follows:
1. A thread must get an object lock associated with it before using a shared resource. If a thread has an object lock of the shared resource, Java runtime system (JVM) will not allow another thread to access the shared resource.
If a thread is trying to access the shared resource at the same time, it is blocked by JVM and has to wait until the resource is available.
2. Only methods or blocks can be synchronized. Variables or classes cannot be synchronized.
3. Only one lock is associated with each object or shared resource.
How can we achieve Synchronization in Java?
There are two ways by which we can achieve or implement synchronization in Java. That is, we can synchronize the object. They are:
1. Synchronized Method
2. Synchronized Block
When we declare a synchronized keyword in the header of a method, it is called synchronized method. Once a method is made synchronized, and thread calls the synchronized method, it gets locked on the method.
All other threads will have to wait for the current thread to release the lock. Using the synchronized keyword, we can synchronize the entire method.
For example, if you want to synchronize the code of show() method, add the synchronize before the method name. The syntax to make method synchronized is as follows:
synchronized void show()
// statements to be synchronized
Since the code inside the method is synchronized, the code will not be available to more than one thread at a time.
Synchronizing a block of code is another way of controlling the execution of thread. The general syntax to make a block of code synchronized is as follows:
// statements to be synchronized
Here, object is a reference variable of an object that has to be locked or synchronized. The statements within the synchronized block are available to only one thread at a time.
In the further tutorial, we will learn programs based on synchronized method and synchronized block.
Why use Synchronization?
The synchronization is mainly used to prevent thread interference and consistency problem.
Hope that you will have understood the basic points of thread synchronization in Java with realtime examples. Here, listed some key points related to java thread synchronization that you keep in mind.
Key Points to Remember
1. There are two types of synchronization: Process synchronization and Thread synchronization.
2. Thread synchronization in Java program is achieved through the monitor (lock) concept.
3. A monitor is an object that can block and resume threads.
4. Every object in Java programming language has an associated monitor.
5. Java programming language supports only two kinds of threads synchronization: Mutual exclusion synchronization and Conditional synchronization.
6. In mutual exclusion synchronization, only a single thread is allowed to have access to code at a time.
7. In conditional synchronization, multiple threads are allowed to work together to get results.
Next ⇒ Synchronized Method in Java⇐ PrevNext ⇒