Java Synchronized

Synchronized comes in picture when we are dealing with multiple threads.

Synchronized keyword allows thread to keep a lock on an object or method for shared resource until the task didn’t get complete.

It helps us to run all our methods or tasks synchronously.

Example :

Below Example class is initiating two threads of Mediator class with join operation. For applying synchronization DataSender instance is passed from Example class to Mediator class.

The Mediator class which is extending a Thread class having a synchronized keyword inside run method. The synchronized keyword will help send() method of DataSender class to actually synchronize.

send() method of DataSender class having a sleep time interval of 1000ms.

The synchronized keyword will force and ask other threads to wait until the current thread didn’t get execute.

OUTPUT :

Another way to synchronized send() method :

Declare method with the synchronized keyword.

last way to synchronized send() method :

Write logic inside synchronized block with also help us to synchronize method.

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0