Skip to content
Tutorials Center
My learning

Topics

Lesson 130 of 201 ยท Concurrency

Locks and Conditions

Learn the java.util.concurrent.locks API - ReentrantLock, tryLock with timeouts, lockInterruptibly, ReadWriteLock, Condition, StampedLock and when to prefer synchronized.

The synchronized keyword is simple and safe, but it's also rigid. A thread waiting for an intrinsic lock can't give up after a timeout, can't be interrupted, and can't check whether the lock is free without waiting. There's only one wait set per object, so producers and consumers have to share it. And every reader excludes every other reader, even when nobody is writing.

The java.util.concurrent.locks package fills those gaps with explicit lock objects. This lesson covers ReentrantLock (a more capable synchronized), ReadWriteLock (many readers or one writer), Condition (several wait sets on one lock) and StampedLock (optimistic reads), and finishes with clear advice on when to use which. It assumes you know synchronization and wait and notify.

ReentrantLock basics

A ReentrantLock does what synchronized does, with method calls instead of a block. The pattern is always the same: call lock() right before a try, and unlock() in the finally:

Java
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();                 // ALWAYS in finally
}

With synchronized, the JVM releases the lock automatically when the block ends. An explicit lock is released only when you call unlock(). Forget it, or skip it because of an exception, and the lock stays held forever: every other thread that needs it hangs. That's the price of the extra flexibility.

Java ReentrantLock as a better synchronized

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The count is exactly 400,000, as with synchronized. Inside incrementTwice, the hold count is 1; each nested increment() raises it to 2 and back. Like intrinsic locks, ReentrantLock is reentrant: the thread that holds it can lock it again, and the lock keeps a hold count. It's released only when unlock() has been called as many times as lock(). Calling unlock() on a lock you don't hold throws IllegalMonitorStateException.

ReentrantLock also has inspection methods intrinsic locks lack: isLocked(), isHeldByCurrentThread(), getHoldCount(), hasQueuedThreads() and getQueueLength(). They're useful in assertions and monitoring, not for program logic, since the answer may change right after you read it.

tryLock: don't wait forever

tryLock() takes the lock only if it's free right now and returns true, or returns false immediately. tryLock(time, unit) waits up to the given time. This is how you avoid deadlocks and keep a slow resource from freezing everyone who needs it:

Java tryLock with and without a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first attempt fails at once, the second fails after about 50 ms, and the third waits until the long job finishes and then succeeds. The pattern matters: only call unlock() if tryLock returned true, so the try/finally starts after the successful check.

The no-argument tryLock() barges: it takes a free lock even if other threads are queued, and even on a fair lock. The timed tryLock(time, unit) respects fairness. Both are the right choice when doing something else is better than waiting: skip this cache refresh, try another replica, show "busy" to the user.

lockInterruptibly: waiting you can cancel

A thread waiting to enter synchronized ignores interrupts (Thread Lifecycle). lockInterruptibly() waits like lock(), but throws InterruptedException if the thread is interrupted while waiting. Use it for tasks that must stay cancellable, for example when an executor is shutting down:

Java Cancelling a thread that waits for a lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The waiter is in the WAITING state (explicit locks park threads rather than blocking them on a monitor), and the interrupt gets it out. With synchronized or plain lock(), it would have waited until main released the lock.

Fairness

new ReentrantLock(true) creates a fair lock: when it's released, the thread that has waited longest gets it. The default (false), like synchronized, is unfair: a newly arriving thread may grab the lock ahead of the queue. Unfair locks have much higher throughput, because handing a lock to a parked thread means waking it up, which is slow, while a thread that's already running can take it at once. Use a fair lock only when you've seen starvation and predictable ordering matters more than speed.

ReadWriteLock: many readers or one writer

Lots of shared data is read far more often than it's written: configuration, caches, reference data. With a normal lock, readers exclude each other even though reading together is perfectly safe. A ReadWriteLock has two locks:

  • the read lock, which any number of threads can hold at the same time, as long as no one holds the write lock;
  • the write lock, which is exclusive: while a thread holds it, no other thread can read or write.
Java A cache with ReentrantReadWriteLock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Several readers were inside together (usually all 5), while the writer saw zero readers during its write: it waited until they had all left. Rules and caveats for ReentrantReadWriteLock:

  • A thread holding the write lock may also take the read lock (downgrading: lock read, then unlock write).
  • A thread holding the read lock can not upgrade to the write lock. Calling writeLock().lock() while holding the read lock deadlocks the thread with itself. Release the read lock first, then re-check the data after taking the write lock.
  • It only pays off when reads are frequent, take some time, and writes are rare. For tiny critical sections, a plain lock is often faster. For maps, ConcurrentHashMap usually beats both (Concurrent Collections).

Condition: several wait sets on one lock

Condition is to ReentrantLock what wait/notify is to synchronized, with one big improvement: one lock can have several conditions. The bounded buffer needed notifyAll() because producers and consumers shared one wait set. With two conditions, notFull and notEmpty, each signal() reaches the right kind of thread:

Monitor method Condition method
wait() await()
wait(ms) await(time, unit) / awaitNanos(n)
notify() signal()
notifyAll() signalAll()
Java A bounded buffer with two Conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three producers and one consumer share a buffer of only two slots, and every item arrives. (The order of arrival varies, so the example sorts the list before printing.) Because producers only wait on notFull and consumers only on notEmpty, a single signal() is safe here and wakes exactly one thread that can use it.

The wait/notify rules carry over unchanged: hold the lock when calling await or signal, always await in a while loop, and handle InterruptedException. (awaitUninterruptibly() exists for the rare case where you must not be interrupted.) Don't confuse Condition.await() with Object.wait(): a Condition is still an Object, so notFull.wait() compiles, but it's the wrong method and throws IllegalMonitorStateException.

StampedLock: optimistic reads

StampedLock (Java 8) is a specialist for read-heavy code where even taking a read lock is too expensive. Its trick is the optimistic read: you don't lock at all; you get a stamp, read the fields into local variables, then ask validate(stamp) whether a write happened in the meantime. If not, your copy is consistent. If so, fall back to a real read lock.

Java Optimistic reading with StampedLock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first call validates and returns 5.0 without ever locking. In the second, a write lands between reading the fields and validating, so validation fails and the retry under a read lock returns 10.0. Important limits:

  • StampedLock is not reentrant. Locking it again from the same thread deadlocks.
  • It doesn't support Conditions, and the stamps must be passed back exactly.
  • In the optimistic section, the values you read may be inconsistent until validated: never act on them (follow a reference, index an array) before validate succeeds.

Use it in low-level, performance-critical classes after measuring. For everyday code, ReentrantReadWriteLock or plain locks are far easier to get right.

Lock or synchronized?

synchronized ReentrantLock
Released automatically yes, at the end of the block no, unlock() in finally
Reentrant yes yes
Try without waiting / with timeout no tryLock(), tryLock(time, unit)
Interruptible while waiting no lockInterruptibly()
Fairness option no (unfair) new ReentrantLock(true)
Wait sets one per object (wait/notify) any number of Conditions
Lock across methods no, block-structured yes (but be careful)
Inspection Thread.holdsLock(obj) only isLocked, getHoldCount, queue info
Shows in thread dumps yes yes

The advice:

  • Default to synchronized. It's shorter, can't leak a held lock, and modern JVMs make it fast. Since Java 24, it also no longer pins virtual threads to their carrier, which removed the main reason many projects had switched to ReentrantLock.
  • Use ReentrantLock when you need one of its features: timeouts, interruptible waiting, fairness, or several conditions.
  • Use ReadWriteLock for read-mostly data with non-trivial reads; StampedLock only for measured hot spots.
  • Prefer higher-level tools when they fit: ConcurrentHashMap, BlockingQueue, atomic variables and executors need no hand-written locking at all.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must lock.unlock() be inside a finally block?

    Unlike synchronized, an explicit lock is never released automatically. try/finally guarantees the release on every path, including exceptions.
  2. 2. What does lock.tryLock() do when another thread holds the lock?

    The no-argument tryLock never waits. tryLock(time, unit) waits up to the timeout; both return true only when the lock was acquired.
  3. 3. A thread holds the read lock of a ReentrantReadWriteLock and calls writeLock().lock(). What happens?

    ReentrantReadWriteLock does not support upgrading. Release the read lock, acquire the write lock, then re-check the state, since it may have changed in between.
  4. 4. Why can the bounded buffer with notFull and notEmpty Conditions safely use signal() instead of signalAll()?

    Producers wait only on notFull and consumers only on notEmpty. A signal on notEmpty can only wake a consumer, which is exactly who can use the new item.
  5. 5. What does StampedLock.validate(stamp) return after an optimistic read if a write lock was taken in the meantime?

    A failed validation means a write happened after the stamp was issued. The usual pattern falls back to readLock() and re-reads the fields.

Summary

  • ReentrantLock is an explicit, reentrant lock: lock() before try, unlock() in finally, always.
  • tryLock() and tryLock(time, unit) avoid waiting forever (unlock only on success); lockInterruptibly() lets a waiting thread be cancelled.
  • Fair locks hand over in arrival order at a large throughput cost; the default is unfair, like synchronized.
  • ReentrantReadWriteLock allows many readers or one writer; it supports downgrading but not upgrading.
  • Condition (await/signal) gives one lock several wait sets, so signals reach the right threads; keep the while loop.
  • StampedLock offers optimistic reads for hot, read-mostly code; it's not reentrant and needs validate.
  • Default to synchronized; choose explicit locks for timeouts, interruptibility, fairness or multiple conditions.

Next: Atomic Variables, where you'll update shared counters and references safely without any locks.