blog

Home / DeveloperSection / Blogs / What are synchronized methods and blocks in Java?

What are synchronized methods and blocks in Java?

What are synchronized methods and blocks in Java?

Ashutosh Kumar Verma 154 23-Jul-2024

This is important to prevent concurrent access issues such as data corruption or instability in multithreaded environments.

 

Synchronized Methods

Synchronized method Method of reporting the synchronized keyword. When a thread calls a synchronized method, it automatically acquires an internal lock (or monitor lock) for the object in that method. This prevents other threads from calling any synchronized methods at the same time in the same object view.

 

Example of a synchronized method

public class Counter {
   private int count = 0;
   public synchronized void increment() {
       count++;
   }
   public synchronized int getCount() {
       return count;
   }
}

 

This example combines the increment() and getCount() methods. This ensures that only one thread can execute increment() or getCount() on the Counter instance at any given time. When one thread executes an increment(), the other thread must wait until the first thread finishes processing the method.


Synchronized Blocks

Synchronized blocks are used to provide synchronized access to a specific block of code instead of an entire method. This allows for better synchronization control.

 

Syntax of synchronized block

synchronized (object) {
   // synchronized code block
}


Object 

Refers to the object in which the horn was found. Any single thread can access the lock of a given object.

Example

public class SharedResource {
   private final Object lock = new Object();
   private int sharedVariable = 0;
   public void modifySharedVariable() {
       synchronized (lock) {
           sharedVariable++;
       }
   }
   public int getSharedVariable() {
       synchronized (lock) {
           return sharedVariable;
       }
   }
}

In the above example 

The modifySharedVariable() and getSharedVariable() methods use the lock object as a monitor to synchronize access to the sharedVariable. This ensures that if one thread executes modifySharedVariable(), the other thread cannot execute modifySharedVariable() or getSharedVariable() unless the lock is released.

 

Key Differences

 

Scope of Synchronization

 

  • Synchronized methods- Synchronize the entire body of the method. If all the work in a method needs to be done, it is easier.

  • Synchronized blocks- Synchronize a specific block of code, allowing better control over parts of the method that need synchronization.

 

Lock Acquisition


Synchronized methods- Use this implicitly as an object launcher (on object instance calls to the method).


Synchronized blocks- Explicitly identify the object on which the lock can be obtained to enable synchronization changes.

 

Performance Considerations

Synchronized blocks- Allow more granular control and can be more efficient than synchronizing entire methods, especially in situations where all method code does not need to be synchronized

 

When to Use


Synchronized methods- Used when all methods need to be planned and ease of lockout is desired.


Synchronized blocks- Used when synchronization is required for a particular block of code or when multiple locks are to be obtained on different parts of the method.

 


Synchronized methods and blocks are key tools for ensuring thread safety and preventing data corruption in concurrent Java programs. They allow maintenance to shared resources and ensure that only one thread can switch resources at a time, thus maintaining consistency and correctness in multithreaded environments

 

 

Also, Read: Discuss the volatile keyword in Java and its role in concurrency.


Updated 23-Jul-2024
Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By