Category: java
synchronized vs ReentrantLock
Published on 27 Oct 2026
Explanation
Both provide mutual exclusion and memory visibility. synchronized releases its monitor automatically when leaving the block. ReentrantLock offers additional capabilities such as timed acquisition, interruptible acquisition, and multiple Condition objects.
Code:
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockDemo {
private final ReentrantLock lock = new ReentrantLock();
public void work() {
lock.lock();
try { System.out.println("Protected work"); }
finally { lock.unlock(); }
}
}
Explanation
When using ReentrantLock, place unlock() in a finally block so exceptions do not leave the lock held. Forgetting to unlock can cause other threads to wait indefinitely.
Code:
import java.util.concurrent.locks.ReentrantLock;
public class LockFinallyDemo {
private final ReentrantLock lock = new ReentrantLock();
public void update() {
lock.lock();
try { System.out.println("Updating"); }
finally { lock.unlock(); }
}
}
Explanation
tryLock() returns immediately if the lock cannot be acquired. The timed overload waits up to a specified duration and can be interrupted. These options can help build responsive lock acquisition strategies.
Code:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TimedLockDemo {
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try { System.out.println("Acquired"); }
finally { lock.unlock(); }
}
}
}
Explanation
Condition provides await(), signal(), and signalAll() operations associated with a ReentrantLock. It supports multiple condition queues for a lock, which can be useful for producer-consumer coordination.
Code:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionDemo {
private final ReentrantLock lock = new ReentrantLock();
private final Condition ready = lock.newCondition();
private boolean available;
public void awaitReady() throws InterruptedException {
lock.lock();
try { while (!available) ready.await(); }
finally { lock.unlock(); }
}
public void signalReady() {
lock.lock();
try { available = true; ready.signalAll(); }
finally { lock.unlock(); }
}
}
Explanation
Use synchronized for straightforward critical sections because it is simple and automatically releases the monitor. Choose ReentrantLock when you need timed or interruptible lock acquisition, tryLock(), or multiple conditions.
Code:
class SimpleCounter {
private int value;
public synchronized void increment() { value++; }
public synchronized int get() { return value; }
}