Synchronization In Java
By AmarSivas | | Updated : 2021-03-12 | Viewed : 7457 times

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.
Table of Contents:
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.
For Sharable sharableObject = new Sharable();
Thread threadOne = new Thread(sharableObject, "thread-1");
Thread threadTwo = new Thread(sharableObject, "thread-2");
Suppose
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.
What is Synchronization in Java?
As we discussed earlier
What is synchronized keyword?
What is the synchronized method?
Please look into the below-given example
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;
}
}
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
What is synchronized block?
The keyword
Please find the code snippet for the synchornized block.
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