Why this matters
- A lock you cannot time out of turns a slow dependency into a total outage, and
tryLockwith a timeout is the one-line defence. - Thread pool sizing is one of the few numbers in a backend service that has a principled formula rather than a guess.
- Choosing the wrong executor factory method is how an application ends up with an unbounded queue that quietly becomes an
OutOfMemoryError.
ReentrantLock
The same mutual exclusion as synchronized, with the lifecycle made explicit.
The finally is not optional. synchronized releases its monitor automatically when the block exits; an
explicit lock does not, and a missed unlock deadlocks everything that follows.
| Aspect | synchronized | ReentrantLock |
|---|---|---|
| Release | Automatic on block exit | Manual — you must call unlock in finally |
| Timeout | Not possible | tryLock(time, unit) |
| Interruptible while waiting | No | lockInterruptibly() |
| Fairness | No ordering guarantee | Optional FIFO ordering |
| Wait conditions | One, via wait/notify | Several, via newCondition() |
| Can span methods | No — block-scoped | Yes — lock here, unlock there |
| Readability | Better; harder to misuse | More capable; easier to leak |
Release
synchronizedAutomatic on block exitReentrantLockManual — you must call unlock in finallyTimeout
synchronizedNot possibleReentrantLocktryLock(time, unit)Interruptible while waiting
synchronizedNoReentrantLocklockInterruptibly()Fairness
synchronizedNo ordering guaranteeReentrantLockOptional FIFO orderingWait conditions
synchronizedOne, via wait/notifyReentrantLockSeveral, via newCondition()Can span methods
synchronizedNo — block-scopedReentrantLockYes — lock here, unlock thereReadability
synchronizedBetter; harder to misuseReentrantLockMore capable; easier to leak
Default to synchronized. Reach for ReentrantLock when you specifically need one of these features.
tryLock, the feature worth knowing
This converts an indefinite hang into a fast, visible failure. In a request-serving application that is almost always the better outcome — a timeout is a problem you can see in a dashboard, whereas a thread blocked forever looks like nothing at all until the pool is exhausted.
ReadWriteLock
When reads vastly outnumber writes, allowing concurrent readers is a large win.
- Many readers, or one writer — never both.
- A waiting writer blocks new readers, so readers cannot starve the writer indefinitely.
- You cannot upgrade a read lock to a write lock; attempting it deadlocks. Release and reacquire instead.
StampedLockadds optimistic reading, which is faster still but considerably easier to misuse.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- StampedLock
- Executors
- Sizing a pool
- Shutting down
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.