In Java, the synchronized
keyword is used to handle thread synchronization. It ensures that only one thread can access a synchronized method or block at a time, thereby preventing race conditions and ensuring thread safety.
Where is synchronized
Used?
- Synchronized Methods: Restrict access to a method so that only one thread can execute it at a time.
- Synchronized Blocks: Restrict access to a specific section of code within a method.
Why Use synchronized
?
When multiple threads try to access shared resources (like variables or objects) concurrently, it can lead to inconsistent or incorrect results. The synchronized
keyword ensures that only one thread accesses a critical section at any given time, preserving data consistency.
How Does synchronized
Work?
Every object in Java has an intrinsic lock (or monitor) associated with it. When a thread enters a synchronized method or block, it acquires the lock. Other threads attempting to enter a synchronized section on the same object must wait until the lock is released.
Types of synchronized
Usage
1. Synchronized Methods
A method can be declared synchronized
, which locks the entire method.
Example:
class Counter {
private int count = 0;
// Synchronized method
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
// Multiple threads increment the counter
Thread t1 = new Thread(() -> counter.increment());
Thread t2 = new Thread(() -> counter.increment());
t1.start();
t2.start();
}
}
Explanation:
- The
increment
method is synchronized. Only one thread can execute it at a time, ensuringcount
is updated safely.
2. Synchronized Blocks
Instead of locking the entire method, you can synchronize only a specific block of code.
Example:
class Counter {
private int count = 0;
public void increment() {
// Synchronized block
synchronized (this) {
count++;
}
}
public int getCount() {
return count;
}
}
Explanation:
- The
synchronized
block locks only the critical section of code, improving efficiency by not locking the entire method.3. Static Synchronized Methods
A static synchronized method locks the class object, not an instance.
Example:
class SharedResource {
public static synchronized void displayMessage(String message) {
System.out.println("Message: " + message);
}
}
Explanation:
- Only one thread can execute a static synchronized method on the class at a time.
Important Points About synchronized
- Locks: Each object has a single intrinsic lock. For synchronized static methods, the class itself is locked.
- Performance: Synchronization adds overhead, so use it only when necessary.
- Deadlocks: Be cautious while using multiple synchronized blocks to avoid deadlocks.
- Reentrancy: The
synchronized
keyword is reentrant, meaning a thread can acquire the same lock multiple times without blocking itself.
When to Avoid synchronized
- If the operation is read-only and no shared resource is being modified, synchronization is unnecessary.
- Use high-level concurrency utilities like
java.util.concurrent
for better performance in complex scenarios.