ProLesson 9.6Advanced3 min readUpdated 30 October 2026
Locks: ReentrantLock and ReadWriteLock
When synchronized isn't enough. Use ReentrantLock for try-lock and timeouts, ReadWriteLock for read-heavy data, and always unlock in finally.
synchronized is simple and good enough for most code. The java.util.concurrent.locks package gives you more control when you need it: trying a lock without waiting forever, timeouts, fairness, and separate read and write locks.
01ReentrantLock
LockDemo.java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Account {
private final Lock lock = new ReentrantLock();
private double balance = 1000;
boolean withdraw(double amount) {
lock.lock();
try { // ALWAYS: lock, then try / finally unlock
if (amount > balance) return false;
balance -= amount;
return true;
} finally {
lock.unlock();
}
}
double balance() {
lock.lock();
try {
return balance;
} finally {
lock.unlock();
}
}
}
public class LockDemo {
public static void main(String[] args) throws InterruptedException {
Account acc = new Account();
Thread a = new Thread(() -> { for (int i = 0; i < 100; i++) acc.withdraw(5); });
Thread b = new Thread(() -> { for (int i = 0; i < 100; i++) acc.withdraw(5); });
a.start(); b.start(); a.join(); b.join();
System.out.println("Balance: " + acc.balance());
}
}Balance: 0.0
Loading the rest of the lesson…