Both synchronized and ReentrantLock are used for mutual exclusion in Java (i.e., only one thread can execute a critical section at a time), but they have key differences in capabilities, flexibility, and usage style.
Let’s break it down:
⚖️ synchronized vs ReentrantLock
| Feature | synchronized | ReentrantLock |
|---|---|---|
| 🧵 Reentrancy | ✅ Yes | ✅ Yes |
| 🔐 Explicit lock/unlock | ❌ No — handled automatically by JVM | ✅ Yes — must explicitly lock()/unlock() |
| ⚠️ Must unlock manually | ❌ No — released when block/method exits | ✅ Yes — always use try-finally |
| ⏱ Timeout support | ❌ No | ✅ Yes (tryLock(timeout)) |
| 🔁 Fairness control | ❌ No | ✅ Yes (new ReentrantLock(true)) |
| 🧪 Condition variables | ❌ No — uses wait()/notify() | ✅ Yes — via lock.newCondition() |
| 💥 Interruptible lock attempts | ❌ No — can’t interrupt waiting thread | ✅ Yes — use lockInterruptibly() |
| 🧠 Readability | ✅ Very easy & clean | ❌ More verbose |
| 🧹 Auto-release on exception | ✅ Yes — auto-release | ❌ No — must use finally |
✅ 1. synchronized (Built-in Monitor Lock)
synchronized(myObject) {
// Critical section
}
Automatically releases lock when the block exits.
Simpler, cleaner syntax.
Ideal for basic mutual exclusion.
✅ 2. ReentrantLock (From java.util.concurrent.locks)
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// Critical section
} finally {
lock.unlock(); // Must be called!
}
More powerful and flexible.
Useful when you need:
- Timeouts
- Non-blocking try-locks
- Multiple conditions
- Interruptible lock attempts
🔄 Example: Timeout with ReentrantLock
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try {
// critical section
} finally {
lock.unlock();
}
} else {
System.out.println("Could not acquire lock in time.");
}
🧠 Summary — When to Use What?
| Use Case | Recommended Approach |
|---|---|
| Simple mutual exclusion | ✅ synchronized |
| Need timeout or fairness | ✅ ReentrantLock |
| Need multiple condition variables | ✅ ReentrantLock |
| Want auto-release on exceptions | ✅ synchronized |
| Want interruptible lock attempts | ✅ ReentrantLock |