Synchronization is a big concept in terms of the Java Multi-Threading, before going to what is a Synchronization will see the below example.
In this example lets try to print the numbers from 1 to 10 by sharing the Integer class object using two threads.
From the above example, we see the number should print from 1 to 10 but the output came as the following.
If we see the above output, the numbers are not printing in the sequential order instead of sequential order its printing like a random numbers(Output may vary from processor to processor). This is one of the classical example of thread sync issues.
Root Cause of this issue is we are using a shared resource or Object using across two threads caused this issue, in our example Integer Class Object is a shared resource. Solution for this problem is nothing but a synchronization.
Synchronization is a concept where the Shared Resource across the threads will used or consumed by a single thread at any given point of time is nothing but a synchronization.
In Java Synchronization can be implemented by following 3 ways.
Lets add the Synchronization block to the above output and see the output how it works.