Video in progress

What does ReentrantLock do better than synchronized, and when do you choose it?

ReentrantLock offers tryLock (with a timeout), lockInterruptibly, a fair mode, and several Conditions. If you don't need these, synchronized is simpler and safer, because you can't forget to unlock.

📖 Answer

The main advantage is control over waiting:

private final ReentrantLock lock = new ReentrantLock();

boolean transfer(Account from, Account to, long amount) throws InterruptedException {
    if (!lock.tryLock(200, TimeUnit.MILLISECONDS)) {
        return false;   // busy: we don't sit and wait, we try again later
    }
    try {
        from.debit(amount);
        to.credit(amount);
        return true;
    } finally {
        lock.unlock();   // always in a finally
    }
}

With synchronized, a thread waits forever until it gets the monitor, and you can't wake it with an interrupt either. With ReentrantLock:

  • tryLock() is a practical way to avoid deadlock;
  • lockInterruptibly() lets a waiting thread bail out when the service is shutting down;
  • new ReentrantLock(true) is the fair mode, which grants the lock in queue order (but is noticeably slower);
  • lock.newCondition() gives separate wait queues on one lock for "not full" and "not empty".

The drawback is that it is easy to forget the unlock() in the finally, and if you do, the lock stays held forever.

Java 21 added one more reason: a virtual thread that blocks inside synchronized pins its carrier (fixed in Java 24), while ReentrantLock doesn't do that.