Quiz: ReentrantLock and the Lock Interface in Java: tryLock, ReadWriteLock, Condition

Total: 8 questions

1. 

What are Lock and ReentrantLock in Java, and why is unlock() called in finally?

Lock is an interface from java.util.concurrent.locks (Java 5): an explicit lock and an alternative to synchronized. It adds acquiring without waiting or with a timeout (tryLock), an interruptible wait (lockInterruptibly), a fair queue and several Condition objects on one lock. The main implementation is ReentrantLock.

You release the lock yourself, so the code always follows the same pattern:

lock.lock();          // acquire - before try
try {
    // critical section
} finally {
    lock.unlock();    // release - always in finally
}

unlock() goes in finally because otherwise an exception or an early return leaves the lock taken. The thread can even finish while isLocked() keeps returning true, and every other thread waits forever; synchronized would have released the monitor on its own. lock() goes before try: if the acquisition fails (for example, lockInterruptibly() throws InterruptedException), finally would call unlock() on a lock the thread does not hold and get an IllegalMonitorStateException that hides the original error.

2. 

What methods does the Lock interface have, and how do lock(), lockInterruptibly() and tryLock() differ?

Six methods: four ways to acquire the lock, unlock() and newCondition(). The ways to acquire differ in what they do when the lock is busy:

  • lock() waits as long as it takes. interrupt() does not break the wait: the thread gets the lock with the interrupted flag set.
  • lockInterruptibly() waits, but responds to an interrupt with InterruptedException; it also throws if the flag was set before the call.
  • tryLock() does not wait and returns true or false at once. On a fair lock it barges ahead of the queue.
  • tryLock(time, unit) waits no longer than the timeout, can be interrupted with InterruptedException, and respects fairness.

unlock() releases the lock (on ReentrantLock it decrements the hold count by 1) and throws IllegalMonitorStateException in a thread that does not own it. newCondition() creates a wait condition bound to this lock. A thread waiting in lock() is in the WAITING state, not BLOCKED as with synchronized.

After tryLock() the lock is released only in the branch where it was acquired: if (lock.tryLock()) { try { … } finally { lock.unlock(); } }.

3. 

What does it mean that ReentrantLock is reentrant, and what does getHoldCount() show?

A reentrant lock lets the thread that already owns it call lock() again without waiting. ReentrantLock counts these acquisitions: getHoldCount() returns how many times the current thread has acquired it (0 if it does not own it). The lock is released only when unlock() has been called as many times as lock(). If a method takes the lock twice (itself and through a nested call) but releases it once, other threads wait for no visible reason.

For checks and monitoring there are isHeldByCurrentThread() (handy in an assert), isLocked(), getQueueLength() and isFair(). Do not build "if it is free, take it" logic on isLocked(): that is what tryLock() is for.

A ReentrantLock has an owner, so unlock() from another thread throws IllegalMonitorStateException. If one thread must acquire and another must release, use a Semaphore with one permit.

4. 

What is a fair lock, and why is ReentrantLock unfair by default?

A fair lock - new ReentrantLock(true) - hands a released lock to the thread that has been waiting longest, in queue order (FIFO). This protects a particular thread from starvation.

An unfair lock is faster. Waking up a waiting thread takes time, and in that gap an unfair lock goes to whoever is already running on a CPU and asking for it right now (barging), with no extra context switch. According to the Javadoc, programs using fair locks under contention are slower, "often much slower".

Two caveats:

  • The no-argument tryLock() breaks fairness: it takes a free lock even when other threads are queued. If you need fairness for a no-wait attempt too, call tryLock(0, TimeUnit.SECONDS).
  • A fair lock does not make the thread scheduler fair - it only orders its own queue of waiting threads.
5. 

How does ReentrantLock differ from synchronized, and which one should you use?

Use synchronized by default: the monitor is released automatically on any exit from the block, the code is shorter, and performance has been comparable since Java 6. Reach for ReentrantLock when you need one of its features:

  • acquiring without waiting - tryLock() - or with a timeout - tryLock(time, unit);
  • an interruptible wait - lockInterruptibly() (a BLOCKED thread ignores interrupt());
  • a fair queue - new ReentrantLock(true);
  • several Condition objects on one lock instead of a single wait()/notify() set;
  • separate read and write locks - ReentrantReadWriteLock.

What they share: both are reentrant and give the same visibility guarantees - unlock() happens-before the next lock() of the same lock. A thread waiting for synchronized is BLOCKED; one waiting for ReentrantLock is WAITING or TIMED_WAITING. In Java 21-23 waiting inside synchronized pinned a virtual thread to its carrier, which ReentrantLock never does; since Java 24 (JEP 491) that difference is gone.

Often the right answer is neither: AtomicInteger, ConcurrentHashMap and BlockingQueue already contain the locking you need.

6. 

What is a Condition in Java, and how are await()/signal() better than wait()/notify()?

A Condition is a wait condition bound to a Lock; lock.newCondition() creates it. await(), signal() and signalAll() work like wait(), notify() and notifyAll(): they are called only while holding their lock, and await() releases the lock for the duration of the wait and re-acquires it before returning. Without the lock you get IllegalMonitorStateException.

The main advantage is that one lock can have several conditions. In a bounded buffer producers wait on notFull and consumers on notEmpty, so a single signal() always wakes a thread from the right group, with no wasted wake-ups. ArrayBlockingQueue is built this way.

lock.lock();
try {
    while (items.isEmpty()) {   // while, not if
        notEmpty.await();
    }
    // take an item
} finally {
    lock.unlock();
}

await() always goes inside while: spurious wake-ups and a "stolen" condition are possible. await(time, unit) has a return value - false if the time ran out. A common mistake is writing condition.wait(): that is an Object method, it uses the monitor of the condition object itself and fails with IllegalMonitorStateException.

7. 

How does ReadWriteLock work, and can a read lock be upgraded to a write lock?

A ReadWriteLock is a pair of linked locks. Any number of threads can hold readLock() at the same time while nobody is writing; writeLock() is held by one thread only, with no readers and no other writers. The main implementation is ReentrantReadWriteLock; it pays off when data is read often and for long, and changed rarely (a cache, configuration).

  • Upgrading read → write is impossible. The write lock is granted only when no thread holds a read lock, including the requesting thread itself. writeLock().lock() under readLock() waits forever, and a thread dump does not show it as a deadlock. The correct way is to release read, acquire write and check the data again.
  • Downgrading write → read is allowed: acquire read while holding write, then release write.
  • Only the write lock has Condition; readLock().newCondition() throws UnsupportedOperationException.

For short operations a read-write lock can be slower than a plain one, and for a map a ConcurrentHashMap is simpler: its reads take no lock at all.

8. 

What is StampedLock, and how does it differ from ReentrantReadWriteLock?

StampedLock (Java 8) is a lock with three modes: writing, reading and optimistic reading. In optimistic mode a thread blocks nothing: it gets a stamp from tryOptimisticRead(), reads the fields into local variables and calls validate(stamp). If a write happened in the meantime, it rereads under a regular readLock().

long stamp = sl.tryOptimisticRead();
double curX = x, curY = y;
if (!sl.validate(stamp)) {
    stamp = sl.readLock();
    try {
        curX = x;
        curY = y;
    } finally {
        sl.unlockRead(stamp);
    }
}

When writes are rare, readers almost never take the lock and do not get in the writer's way. Restrictions compared with ReentrantReadWriteLock:

  • not reentrant - a second writeLock() in the same thread waits for itself forever;
  • does not implement Lock (there are asReadLock() and asWriteLock() views);
  • does not support Condition;
  • is released with the stamp received on acquisition.
Page 1 of 1