Java Synchronized

Java 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan