Synchronization In Java

By | | Updated : 2021-03-12 | Viewed : 3806 times

Synchronization In Java

Generally, when you writing the program with multi-threading you might face problems with data consistency. So here we should think twice about the design to avoid data inconsistency problems. One of the design techniques is synchronization to avoid data inconsistency problems.

Usage of Synchronization

We would discuss here one example to know about the necessity of Synchronization.

We have multiple threads holding the shareable object. Threads are trying to modify the state of that sharable object. Here sharable object state can be modified parallelly. But Object state modification should not happen in a parallel manner.

When one thread is trying to modify the object then the internal state of the same object will not be exposable to others. This could cause data inconsistency.

For example, two threads are tiring to modify the one shareable object.

Usage of Synchronization
For Sharable sharableObject = new Sharable();

Thread threadOne = new Thread(sharableObject, "thread-1");
Thread threadTwo = new Thread(sharableObject, "thread-2");

Suppose threadOne changes the state of sharableObject and trying to print the state of the object. while before printing the other thread can change the state of the object. Both data changes on sharableObject will not be in sync as they are in parallel execution.

So both threads can print two different values. Why did it happen like this? When one thread modifying object another thread can not aware of all modifications which are in the thread cache. In other words, one thread's cache will not visible to others. Using synchronization we can override inconsistency problems.

What is Access control?

Before we are going to understand synchronization we need to think about Access Control. One of the aspects required to know when we handle the data with multithreading.

Synchronization deals the problem of data inconsistency with Access control. When one thread occupies the shared object then the lock will be applied on the same object. So it will stop other thread's interaction with the same object as the object got locked.

What is Synchronization in Java?

As we discussed earlier Synchornization deals with access control. It allows the thread to have a lock on a particular object where other threads can not access the lock. Until and unless the lock is released the object will not be accessed by other threads. In Java, we use a keyword called synchronized to achieve get Synchronization on a particular common object.

What is synchronized keyword?

synchronized is the modifier which can be applied to methods and blocks, We can not declare a class with a synchronized keyword. if a method or block is declared as a synchronized two different threads can not access the code block.

Note: We will be discussing the same in the below sections.

What is the synchronized method?

synchronized is keyword can be applied to methods. When a method prefix with keyword synchronized then that method is called as synchornized method. The synchronized method of the Class will allow only one thread for accessing where other threads can not access.

Please look into the below-given example

Sequences.java
 public synchronized void getSequences(int i) {
        int limit = i + 5;
        while (i < limit) {
            String currentThreadName = Thread.currentThread().getName();
            System.out.println("Current Thread  " + currentThreadName + " Sequence: " + i);
            i = i + 1;
        }
    }
ThreadExample.java
public class ThreadExample implements Runnable {

    private final Sequences sequences;

    public ThreadExample(Sequences sequences) {
        this.sequences = sequences;
    }

    @Override
    public void run() {
        sequences.getSequences(5);
    }
}

Here Sequence object is sharable and can be accessed by only one thread. If we remove the synchronized keyword then multiple threads can access it and data will be inconsistent.

What is synchronized block?

The keyword synchronized can also be applicable on the block. Here we have better performance with synchronized methods. The lock will be applicable more number of the statements for a synchronized method where the synchronized block will not. When the number of statements reduced for execution then the waiting period of other threads can be reduced. Hence performance will be improved.

Please find the code snippet for the synchornized block.

synchornizated block on instance
synchronized (this) {
            while (i < limit) {
                String currentThreadName = Thread.currentThread().getName();
                System.out.println("Current Thread  " + currentThreadName + " Sequence: " + i);
                i = i + 1;
            }
        }

Please refer to the Github repository for the remaining example for the Synchronization-Example-App

Advantage & Disadvantage

synchronized keyword:The main advantage of the synchronized keyword is where we can resolve the data inconsistency problems. But the main disadvantage of the synchronized keyword is increases the waiting time of the thread and impacts the performance of the system.

Locking: Each object/class in Java can have a locking mechanism in which an object's state can be handled properly. Acquiring and releasing the lock taken care of by JVM. We will discuss in detail later about locking ie object vs class lock.

Leave A Reply