Synchronized method

  • Eclipse: Oxygen
  • Java: 1.8

Synchronized method

Synchronization is the ability to control the access of multiple threads to any shared resource.

Types of Synchronization

  1. Synchronized method
  2. Synchronized block
  3. Static synchronization

Let us discuss the synchronized method

The synchronized method is used to put a lock on a single object accessing the same entity (method) such as generate. The synchronized block is useless when there are different assigned objects since it uses MONITORS that are special types of blocks. Therefore, synchronized use will only guarantee a lock for a single object.

Without using the synchronization method we will get multiple outputs every time because both threads are getting execute simultaneously.

Output

[[[[[]]]]][[[[[]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

In the following program, if you declare any method as a synchronized, it is known as a synchronized method.

A synchronized method is used to prevent this public void generate() method to get executed on multiple threads simultaneously.

Making a method synchronized means that, this synchronized public void generate() method will not get executed multiple threads.

So, if more than one thread has a reference to the same method then only one thread can execute this method at a specific point of time. As a result, we will get consistency in output.

Output

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

[[[[[]]]]]

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu