How do synchronized and ReentrantLock differ? When would you use ReadWriteLock or StampedLock?
Short answer
Both are reentrant locks with the same visibility semantics. synchronized is concise, releases automatically, and is enough for most cases; ReentrantLock adds tryLock with timeout, lockInterruptibly, fairness, several Conditions, at the cost of calling unlock() yourself.
3 points to say:
- Default to
synchronized; useReentrantLockfor timeout, interrupt, fairness, severalConditions, and alwaysunlock()infinally. ReadWriteLock: many readers at once when reads dominate; you cannot upgrade read → write.StampedLock: adds optimistic reads but is not reentrant.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.