Java Locks: ReentrantLock, tryLock, ReadWriteLock and CyclicBarrier (OCP 21)
The Lock framework and coordination tools for the OCP 21 exam: ReentrantLock with lock, unlock and tryLock, fairness, hold counts, IllegalMonitorStateException, ReentrantReadWriteLock, CyclicBarrier with barrier actions, plus CountDownLatch and Semaphore.
kvi5hnuCode Sprout team member8 min readOn this page
A synchronized block (article 80) is simple, but it's all or nothing: a thread that can't get the lock waits, possibly forever, and can't give up or do something else. The Lock framework in java.util.concurrent.locks gives the same mutual exclusion with more control. This article also covers tools that coordinate groups of threads: CyclicBarrier, which the exam tests, and CountDownLatch and Semaphore, which you'll meet in real code and in earlier examples of this course.
The Lock interface and ReentrantLock
Lock is an interface, so new Lock() doesn't compile. The implementation you need is ReentrantLock:
private final Lock lock = new ReentrantLock();
private int bookings;
void book() {
lock.lock(); // wait until this thread holds the lock
try {
bookings++; // protected code
} finally {
lock.unlock(); // ALWAYS release it
}
}
This has the same effect as a synchronized block, with one big difference: nothing releases the lock for you. If you forget unlock(), or an exception skips it, the lock stays held, even after the owning thread ends, and every other thread that calls lock() waits forever. That's why unlock() goes in a finally block.
Lock methods
| Method | Behavior |
|---|---|
void lock() | waits, as long as needed, until the lock is acquired |
void unlock() | releases the lock |
boolean tryLock() | takes the lock if it's free right now and returns true. Otherwise it returns false immediately, without waiting. |
boolean tryLock(long time, TimeUnit unit) | waits up to the given time. Returns true if it got the lock, or false on timeout. Throws InterruptedException. |
void lockInterruptibly() | like lock(), but stops waiting if the thread is interrupted. Throws InterruptedException. |
tryLock lets a thread do something else instead of waiting:
if (desk.tryLock()) {
try {
System.out.println("serving the customer");
} finally {
desk.unlock(); // release only if tryLock returned true
}
} else {
System.out.println("desk busy, answering e-mail instead");
}
Always check the result of tryLock(). Unlock only when it returned true, because unlocking a lock you don't hold throws an exception.
Rules to remember
IllegalMonitorStateException: callingunlock()on a lock the current thread doesn't hold throws this unchecked exception.new ReentrantLock().unlock()is the classic exam example.- Reentrant: the thread holding a
ReentrantLockcan lock it again. The lock keeps a hold count, and other threads can acquire it only afterunlock()has been called as many times as it was locked. Lock twice and unlock once, and another thread'stryLock()still returnsfalse.getHoldCount()exists onReentrantLock, not on theLockinterface. - Fairness:
new ReentrantLock(true)grants the lock to waiting threads roughly in the order they asked. The default (false) is unfair but faster. Use fairness only when order really matters. - No lock sharing with
synchronized:synchronized (myLock)compiles, but it uses the object's built-in monitor, which is unrelated tolock()/unlock().
ReentrantLock versus synchronized
synchronized | ReentrantLock | |
|---|---|---|
| Release | automatic at block end | you must call unlock() (in finally) |
| Try without waiting | no | tryLock() |
| Wait with a timeout | no | tryLock(time, unit) |
| Interruptible wait | no | lockInterruptibly() |
| Fair ordering | no | new ReentrantLock(true) |
| Reentrant | yes | yes |
| Waiting thread state | BLOCKED | WAITING or TIMED_WAITING (it parks) |
ReentrantReadWriteLock: many readers, one writer
When data is read far more often than it's written, letting readers run together improves throughput. A ReentrantReadWriteLock has two linked locks, obtained with readLock() and writeLock(), both of type Lock:
- any number of threads can hold the read lock at the same time, as long as no thread holds the write lock;
- only one thread can hold the write lock, and only while no other thread holds either lock.
var menu = new ReentrantReadWriteLock();
menu.writeLock().lock();
menu.readLock().lock(); // OK: a writer may also read (downgrade)
System.out.println(menu.isWriteLocked()); // true
menu.writeLock().unlock();
System.out.println(menu.getReadLockCount()); // 1: still reading
menu.readLock().unlock();
The order matters. Taking the read lock and then the write lock (an upgrade) waits forever, because the write lock waits for all readers to leave, including the thread itself. Only write-then-read works.
CyclicBarrier: wait for each other
Some jobs come in stages, where every worker must finish stage 1 before anyone starts stage 2. A CyclicBarrier is created with the number of threads, called parties, to wait for:
var afterUnload = new CyclicBarrier(4);
var afterSetup = new CyclicBarrier(4, () -> System.out.println("*** stage ready"));
// each of 4 worker tasks:
unload();
afterUnload.await(); // wait here until all 4 have called await()
setUp();
afterSetup.await(); // the last to arrive runs the barrier action first
perform();

Without the barriers, the output of four workers is mixed, with some still unloading while others perform. With them, every unload comes before every set up, which comes before the action and every perform.
Key facts:
await()throws two checked exceptions:InterruptedExceptionandBrokenBarrierException. ARunnablelambda calling it must catch them. ACallablelambda (one that returns a value) doesn't have to.- The optional barrier action (a
Runnable) runs once each time the barrier trips. It's run by the last thread to arrive, before the others are released. - Cyclic means reusable: after it trips, the count resets. With 3 parties and 9 threads calling
await(), it trips 3 times. - Enough threads must be running. With a pool of 2 threads and a barrier of 3 parties, the third party never arrives, so the program hangs. A timed
await(time, unit)would throwTimeoutExceptionand break the barrier, and every other waiter would getBrokenBarrierException. new CyclicBarrier(0)throwsIllegalArgumentException.
Also useful: CountDownLatch and Semaphore
These aren't named in the Java 21 exam objectives, but they're part of the same package and very common. Earlier examples in this course used CountDownLatch.
CountDownLatch(n): threads callawait()until other threads have calledcountDown()n times. Unlike a barrier, the threads counting down don't wait, and the latch is single use. Once the count reaches 0 it stays there, andawait()returns at once.Semaphore(n): holds n permits.acquire()takes one, waiting if none are left, andrelease()gives it back. It's useful to cap how many threads use a resource at once, such as two chargers shared by six cars.
What's current
- Virtual threads: in Java 21, a virtual thread waiting for a
ReentrantLockunmounts from its carrier, but one blocking insidesynchronizedstays pinned. That's why Java 21 guidance preferredReentrantLockfor virtual threads. Java 24 removed thesynchronizedpinning (JEP 491), so both work well now. StampedLock(Java 8) offers optimistic reads, andPhaser(Java 7) is a more flexible barrier. Neither is on the exam.- Locks and barriers have been in the API since Java 5. Their exam-relevant behavior hasn't changed.
Exam traps from this article
A complete example
A hotel and a stage crew show every tool. A ReentrantLock protects a counter updated a million times. tryLock fails while another thread holds the lock, and tryLock(200 ms) waits and times out. Hold counts show why a lock taken twice must be released twice. A read/write lock lets two readers in together but refuses an upgrade. Two barriers keep four workers in step, and one barrier is reused three times. A barrier that waits for more threads than exist breaks. A latch and a semaphore round it off.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
public class Solution {
private final Lock lock = new ReentrantLock();
private int bookings;
void book() {
lock.lock(); // acquire BEFORE try: if lock() fails, finally must not unlock
try {
bookings++;
} finally {
lock.unlock(); // always released, even if the body throws
}
}
/** Joins consecutive equal entries: [a, a, b] -> "a x2, b". */
static String squash(List<String> log) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < log.size(); ) {
int j = i;
while (j < log.size() && log.get(j).equals(log.get(i))) j++;
if (sb.length() > 0) sb.append(", ");
sb.append(log.get(i)).append(j - i > 1 ? " x" + (j - i) : "");
i = j;
}
return sb.toString();
}
/** Starts a thread that holds the lock until 'release' opens; returns once it holds it. */
static Thread holdInOtherThread(Lock l, CountDownLatch release) throws InterruptedException {
CountDownLatch held = new CountDownLatch(1);
Thread t = Thread.ofPlatform().start(() -> {
l.lock();
try {
held.countDown();
release.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
l.unlock();
}
});
held.await();
return t;
}
static boolean tryInOtherThread(Lock l) throws Exception {
try (ExecutorService one = Executors.newSingleThreadExecutor()) {
return one.submit(() -> {
boolean got = l.tryLock();
if (got) l.unlock();
return got;
}).get();
}
}
public static void main(String[] args) throws Exception {
System.out.println("== 1. ReentrantLock protects a counter");
Solution hotel = new Solution();
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int t = 0; t < 4; t++)
pool.execute(() -> { for (int i = 0; i < 250_000; i++) hotel.book(); });
}
System.out.println(" bookings: " + hotel.bookings);
System.out.println("\n== 2. tryLock() and tryLock(timeout)");
ReentrantLock desk = new ReentrantLock();
CountDownLatch release = new CountDownLatch(1);
Thread clerk = holdInOtherThread(desk, release);
System.out.println(" tryLock() while another thread holds it: " + desk.tryLock());
long start = System.nanoTime();
boolean got = desk.tryLock(200, TimeUnit.MILLISECONDS);
long waited = (System.nanoTime() - start) / 1_000_000;
System.out.println(" tryLock(200 ms): " + got + ", waited at least 200 ms: " + (waited >= 190));
release.countDown();
clerk.join();
if (desk.tryLock()) {
try {
System.out.println(" after the other thread released it, tryLock(): true");
} finally {
desk.unlock();
}
}
System.out.println("\n== 3. Reentrant: unlock as many times as you locked");
desk.lock();
desk.lock();
System.out.println(" hold count after locking twice: " + desk.getHoldCount());
desk.unlock();
System.out.println(" after one unlock, another thread's tryLock(): " + tryInOtherThread(desk));
desk.unlock();
System.out.println(" after the second unlock, another thread's tryLock(): " + tryInOtherThread(desk));
System.out.println("\n== 4. Releasing a lock you don't hold");
try {
new ReentrantLock().unlock();
} catch (IllegalMonitorStateException e) {
System.out.println(" unlock() without lock() -> IllegalMonitorStateException");
}
System.out.println(" new ReentrantLock(true).isFair(): " + new ReentrantLock(true).isFair()
+ ", default isFair(): " + new ReentrantLock().isFair());
System.out.println("\n== 5. ReentrantReadWriteLock");
ReentrantReadWriteLock menu = new ReentrantReadWriteLock();
CountDownLatch readersIn = new CountDownLatch(2);
CountDownLatch readersOut = new CountDownLatch(1);
try (ExecutorService readers = Executors.newFixedThreadPool(2)) {
for (int i = 0; i < 2; i++)
readers.execute(() -> {
menu.readLock().lock();
try {
readersIn.countDown();
readersOut.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
menu.readLock().unlock();
}
});
readersIn.await();
System.out.println(" two threads hold the read lock at once: " + menu.getReadLockCount());
System.out.println(" writeLock().tryLock() while readers are in: " + menu.writeLock().tryLock());
readersOut.countDown();
}
menu.writeLock().lock();
menu.readLock().lock(); // write -> read (downgrade) is allowed
System.out.println(" holding write + read: isWriteLocked=" + menu.isWriteLocked()
+ ", readCount=" + menu.getReadLockCount());
menu.writeLock().unlock();
System.out.println(" after releasing write: isWriteLocked=" + menu.isWriteLocked()
+ ", readCount=" + menu.getReadLockCount());
System.out.println(" read -> write upgrade, tryLock(): " + menu.writeLock().tryLock()
+ " (lock() here would wait forever)");
menu.readLock().unlock();
System.out.println("\n== 6. CyclicBarrier keeps 4 workers in step");
List<String> log = Collections.synchronizedList(new ArrayList<>());
CyclicBarrier afterUnload = new CyclicBarrier(4);
CyclicBarrier afterSetup = new CyclicBarrier(4, () -> log.add("*** stage ready"));
try (ExecutorService crew = Executors.newFixedThreadPool(4)) {
for (int i = 0; i < 4; i++)
crew.submit(() -> {
log.add("unload");
afterUnload.await();
log.add("set up");
afterSetup.await();
log.add("perform");
return null; // Callable, so await()'s checked exceptions are allowed
});
}
System.out.println(" " + squash(log));
System.out.println("\n== 7. A CyclicBarrier is reusable");
AtomicInteger trips = new AtomicInteger();
CyclicBarrier gate = new CyclicBarrier(3, trips::incrementAndGet);
try (ExecutorService nine = Executors.newFixedThreadPool(9)) {
for (int i = 0; i < 9; i++) nine.submit(() -> gate.await());
}
System.out.println(" 9 threads, 3 parties -> barrier tripped " + trips.get() + " times");
System.out.println("\n== 8. Too few threads: the barrier never trips");
CyclicBarrier needsThree = new CyclicBarrier(3);
List<String> outcomes = Collections.synchronizedList(new ArrayList<>());
try (ExecutorService two = Executors.newFixedThreadPool(2)) {
two.submit(() -> {
try { needsThree.await(300, TimeUnit.MILLISECONDS); }
catch (TimeoutException | BrokenBarrierException e) { outcomes.add(e.getClass().getSimpleName()); }
return null;
});
two.submit(() -> {
try { needsThree.await(); }
catch (BrokenBarrierException e) { outcomes.add(e.getClass().getSimpleName()); }
return null;
});
}
Collections.sort(outcomes);
System.out.println(" " + outcomes + ", isBroken=" + needsThree.isBroken());
System.out.println("\n== 9. CountDownLatch: wait for N events, once");
CountDownLatch ovensHot = new CountDownLatch(3);
try (ExecutorService ovens = Executors.newFixedThreadPool(3)) {
for (int i = 0; i < 3; i++) ovens.execute(ovensHot::countDown);
ovensHot.await();
System.out.println(" all 3 counted down, getCount(): " + ovensHot.getCount());
}
ovensHot.countDown();
System.out.println(" counting down again stays at " + ovensHot.getCount()
+ "; await() returns at once: " + ovensHot.await(0, TimeUnit.SECONDS));
System.out.println("\n== 10. Semaphore: at most 2 at a time");
Semaphore chargers = new Semaphore(2);
AtomicInteger inUse = new AtomicInteger();
AtomicInteger peak = new AtomicInteger();
try (ExecutorService cars = Executors.newFixedThreadPool(6)) {
for (int i = 0; i < 6; i++)
cars.submit(() -> {
chargers.acquire();
try {
peak.accumulateAndGet(inUse.incrementAndGet(), Math::max);
Thread.sleep(50);
inUse.decrementAndGet();
} finally {
chargers.release();
}
return null;
});
}
System.out.println(" never more than 2 at once: " + (peak.get() <= 2)
+ ", permits free at the end: " + chargers.availablePermits());
}
}
Output:
== 1. ReentrantLock protects a counter
bookings: 1000000
== 2. tryLock() and tryLock(timeout)
tryLock() while another thread holds it: false
tryLock(200 ms): false, waited at least 200 ms: true
after the other thread released it, tryLock(): true
== 3. Reentrant: unlock as many times as you locked
hold count after locking twice: 2
after one unlock, another thread's tryLock(): false
after the second unlock, another thread's tryLock(): true
== 4. Releasing a lock you don't hold
unlock() without lock() -> IllegalMonitorStateException
new ReentrantLock(true).isFair(): true, default isFair(): false
== 5. ReentrantReadWriteLock
two threads hold the read lock at once: 2
writeLock().tryLock() while readers are in: false
holding write + read: isWriteLocked=true, readCount=1
after releasing write: isWriteLocked=false, readCount=1
read -> write upgrade, tryLock(): false (lock() here would wait forever)
== 6. CyclicBarrier keeps 4 workers in step
unload x4, set up x4, *** stage ready, perform x4
== 7. A CyclicBarrier is reusable
9 threads, 3 parties -> barrier tripped 3 times
== 8. Too few threads: the barrier never trips
[BrokenBarrierException, TimeoutException], isBroken=true
== 9. CountDownLatch: wait for N events, once
all 3 counted down, getCount(): 0
counting down again stays at 0; await() returns at once: true
== 10. Semaphore: at most 2 at a time
never more than 2 at once: true, permits free at the end: 2
Points to notice:
- The lock-protected counter reached exactly 1,000,000, with
lock()placed just beforetryandunlock()infinally. - After one
unlock()of a lock taken twice, another thread still couldn't get it. The hold count had to reach zero first. - Two threads held the read lock together (
getReadLockCount()was 2), butwriteLock().tryLock()failed while they were inside. - The barrier log came out grouped: four
unload, fourset up, the barrier action, then fourperform. - With two threads and three parties, the timed
awaitthrewTimeoutException, and the other waiter gotBrokenBarrierException. - The worker tasks were written as
Callables (return null;) so thatawait()'s checked exceptions didn't need catching inside them.
Common questions
When should I use Lock instead of synchronized?
When you need tryLock, a timeout, interruptible waiting, fairness, or separate read and write locks. Otherwise synchronized is shorter and can't be left locked by mistake.
What's the difference between CyclicBarrier and CountDownLatch?
With a barrier, the same threads wait for each other, and it can be reused. With a latch, one or more threads wait for events counted by other threads, and it can't be reset.
Can the barrier action throw an exception?
If it does, the barrier breaks: the thread that ran it gets the exception, and the other waiting threads get BrokenBarrierException.
Summary
ReentrantLockgives mutual exclusion withlock()/unlock(), plustryLock(),tryLock(time, unit)and optional fairness.- Always release in
finally, exactly once per successful acquire. Releasing an unheld lock throwsIllegalMonitorStateException. ReentrantReadWriteLockallows many readers or one writer. Write-then-read is fine, but read-then-write hangs.CyclicBarriermakes a fixed number of threads wait for each other at each stage. It's reusable and can run a barrier action, but it needs enough threads.CountDownLatch(one-shot countdown) andSemaphore(limited permits) complete the toolbox.
Practice quiz
Test yourself with the locks and CyclicBarrier quiz: 10 exam-style questions with explanations.
Previous: Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)
Next: Java Concurrent Collections and Threading Problems: Deadlock, Starvation and Livelock (OCP 21)
Related reading
- Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
- Java Thread Safety: Race Conditions, volatile, Atomic Classes and synchronized (OCP 21)
- Java ExecutorService: Runnable, Callable, Future, invokeAll and Scheduling (OCP 21)
- Java Threads: Platform and Virtual Threads, Thread States and Interrupting (OCP 21)
- Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.