+91-9990449935

 0120-4256464

Synchronization

Synchronization is the capability of control the access of multiple threads to any shared resource. Synchronization is better in case we want only one thread can access the shared resource at a time.

Why use Synchronization?

The synchronization is mainly used to

  1. To prevent thread interference.
  2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

  1. Process Synchronization
  2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

  • Mutual Exclusive
  1. Synchronized method.
  2. Synchronized block.
  3. static synchronization.
  • Cooperation (Inter-thread communication)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:

  1. by synchronized method
  2. by synchronized block
  3. by static synchronization

Understanding the concept of Lock

Synchronization is built around an internal entity known as the lock or monitor.Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

Output: 5
       100
       10
       200
       15
       300
       20
       400
       25
       500
       

Solution by synchronized method

  • If you declare any method as synchronized, it is known as synchronized method.
  • Synchronized method is used to lock an object for any shared resource.
  • When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the method returns.
Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
       

Same Example of synchronized method by using annonymous class

In this program, we have created the two threads by annonymous class, so less coding is required.

Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500