SteelReed

Search

Search posts, questions…

ConcurrencyQuestion 7 / 19

Middle

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.

yesnonoyesNeed to guard shared dataMostly reads, few writes?ReadWriteLockor StampedLockNeed timeout, interrupt,fairness?synchronizedReentrantLockunlock in finally

3 points to say:

  1. Default to synchronized; use ReentrantLock for timeout, interrupt, fairness, several Conditions, and always unlock() in finally.
  2. ReadWriteLock: many readers at once when reads dominate; you cannot upgrade read → write.
  3. 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.