Java Synchronization

Java Synchronization is a concept which controls the accessing of a shared resource or an Object by only one thread at a time. If multiple threads are trying to access a single object, there might be heavy chances of the Object values gets overridden or corrupted.

In these conditions synchronization is helpful to regulate the accessing of a shared resource or an object by multiple threads. Synchronization helps to allow only one thread at a time to access the shared resource, if the synchronization is implemented properly.

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.

What is 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.

  • Class Level Synchronization
  • Object Level Synchronization.
  • Anonymous Synchronization block.

Lets add the Synchronization block to the above output and see the output how it works.

Output

<-PREV NEXT->