The Plain Picture#
The room key from Chapter 3 is fine for simple cases. Sometimes you want a smarter key: "try the door, and if it's locked, don't wait forever — come back in 300 ms", or "any number of people may read the notice board together, but whoever writes on it needs the room alone".
The Real Names#
ReentrantLock(java.util.concurrent.locks) does whatsynchronizeddoes, plus:tryLock()/tryLock(timeout, unit)— attempt without waiting forever;lockInterruptibly()— can be interrupted while waiting;optional fairness (
new ReentrantLock(true): longest-waiting thread goes next — slower, prevents starvation);Conditionobjects (lock.newCondition()) for waiting/signalling.
You must unlock in
finally:Java lock.lock(); try { /* critical section */ } finally { lock.unlock(); } // forget this once and the lock is held foreverReentrantReadWriteLock— many readers at once, or one writer alone. Good for data read far more often than written (a config cache).StampedLock— a faster read/write lock with an "optimistic read" mode; advanced.
Under the Hood — making a deadlock, then escaping it#
The classic deadlock (Operating Systems Ch 9): thread 1 locks A then wants B; thread 2 locks B then wants A. With plain lock() they'd freeze forever.
With tryLock and a timeout, each gives up instead:
ReentrantLock a = new ReentrantLock(),
b = new ReentrantLock();
// thread 1: a.lock(); ... if (b.tryLock(300, MILLISECONDS)) { ... } else return "T1 gave up waiting for B";
// thread 2: b.lock(); ... if (a.tryLock(300, MILLISECONDS)) { ... } else return "T2 gave up waiting for A";T1 gave up waiting for B | T2 gave up waiting for A(A latch made both threads grab their first lock before trying the second, so the deadlock was guaranteed.) Timeouts break the no preemption condition from Operating Systems Ch 9: the thread gives up its claim and can retry. The better fix is still a global lock order — always lock the lower-ID account first — which removes the circular wait entirely.
Finding deadlocks in a running Java program: jstack <pid> (or jcmd <pid> Thread.print) prints every thread's stack and ends with
"Found one Java-level deadlock:" listing the threads and locks involved (Inside the JVM).
synchronized or ReentrantLock? Use synchronized by default — simpler, can't forget to unlock. Use ReentrantLock when you need tryLock, timeouts,
interruptible waiting, fairness, or multiple conditions.
Check yourself
4 questionsName three things ReentrantLock can do that synchronized can't.
Show answerHide answer
Any three: tryLock, timeouts, interruptible lock waiting, fairness, multiple Condition objects.
Why must unlock() be in a finally block?
Show answerHide answer
If the critical section throws, the lock would otherwise never be released, blocking every other thread forever.
How does tryLock with a timeout prevent a permanent deadlock? What's the better prevention?
Show answerHide answer
A thread that can't get the second lock in time gives up and releases what it holds (breaking "no preemption"); a consistent global lock order prevents the circular wait altogether.
When is a read-write lock useful?
Show answerHide answer
When data is read much more often than written — many readers can proceed together, writers get exclusive access.