Synchronized Block Vs Synchronized Method
Synchronized Block Vs Synchronized Method
1. Synchronized Method
When you use the synchronized keyword in a method declaration, it locks the entire method, meaning only one thread can execute that
method on a particular instance of the class at any given time.
How it works:
• When a thread calls a synchronized method, it locks the object (or the class if the method is static) until the method completes.
• This ensures thread safety but may reduce concurrency since the entire method is locked, even if only part of the method
actually requires synchronization.
When to use:
• Use a synchronized method when you need to lock the entire method to ensure that only one thread accesses it at a time, especially
if all code within the method works with shared resources.
•
Example
This example simulates a scenario where multiple threads are trying to update a shared resource, like a bank account balance. Using a
synchronized method ensures that only one thread can access the critical section at a time
package com.example.demo.threads;
class BankAccount {
private int balance = 1000; // Shared resource
balance += amount;
System.out.println(Thread.currentThread().getName() + " completed deposit. New balance: " + balance);
}
}
}
How It Works:
Key Points:
______________________________________________________________________________________________________________
2. Synchronized Block
• A synchronized block allows you to synchronize only a specific part of a method instead of the entire method. You can
specify the object to lock, providing more flexibility and finer control.
How it works:
• The synchronized block allows you to lock only a critical section within a method, not the entire method.
• You specify an object (lock) to synchronize on (often this or another shared object), and only code within that block is
synchronized.
• This approach enables other threads to execute parts of the method outside the synchronized block, increasing
concurrency.
When to use:
• Use a synchronized block when only a specific part of the method requires thread safety. This can improve performance by
allowing multiple threads to execute non-critical sections concurrently
Example:
package com.example.demo.threads;
class BankAccount {
private int balance = 1000; // Shared resource
private final Object lock = new Object(); // Explicit lock object
How It Works:
2. Synchronized Block:
o Instead of locking the entire method, only the critical section of code (modification of balance) is locked.
o The lock is explicitly defined using a private Object (named lock) to avoid accidental interference with other synchronized blocks
or methods.
3. Thread Safety: The synchronized block ensures that only one thread at a time can execute the critical section, preventing race
conditions.