Locks and conditions
What you will learn
Explicit locks protect shared invariants with more control than a synchronized block. ReentrantLock supports timed acquisition and condition variables. Semaphores bound simultaneous resource use, while latches, barriers and phasers coordinate phases of work.
- Release explicit locks reliably and use timed acquisition.
- Wait for a state predicate using a condition loop.
- Choose a permit limiter or phase coordinator for a finite task.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Use the included bounded pool and shutdown helpers where applicable. The fixture runner also enforces a process deadline.
Protect a shared counter with timed lock acquisition
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { ReentrantLock lock = new ReentrantLock(); int[] count = {0}; ThreadPoolExecutor workers = pool(2, 2); Callable<Void> increment = () -> { if (!lock.tryLock(3, TimeUnit.SECONDS)) throw new TimeoutException(); try { count[0]++; } finally { lock.unlock(); } return null; }; try { Future<Void> a = workers.submit(increment), b = workers.submit(increment); a.get(3, TimeUnit.SECONDS); b.get(3, TimeUnit.SECONDS); System.out.println(count[0]); } finally { stop(workers); } }}Expected output:
2Both increments are protected by the same lock; the futures establish completion before the read. The order of the workers is immaterial.
Lock ownership and timeouts
Acquire a ReentrantLock before entering try/finally; call unlock only after successful acquisition. tryLock(timeout, unit) can return false or throw InterruptedException; lockInterruptibly allows waiting to be interrupted. A reentrant lock may be acquired repeatedly by its owner, but each acquisition needs a matching release. Use a consistent ordering when multiple locks are unavoidable; never wait for dependent tasks while holding a lock they need. ReadWriteLock separates shared reads from exclusive writes; it helps only when measured workloads justify the coordination cost. Do not attempt to upgrade a held read lock to a write lock in ReentrantReadWriteLock; release and reacquire and recheck the predicate.
Condition predicates
A Condition belongs to a lock. awaitNanos releases the lock while waiting and reacquires it before returning; signalAll asks waiters to recheck state. Always test a shared predicate while holding the lock, and loop because a wakeup can be spurious or another waiter can consume the state. Preserve the remaining time budget instead of restarting it on each wakeup. Signal under the lock after changing the guarded state. The mailbox below has a one-time publication predicate; a reusable buffer also needs a capacity predicate.
Coordination versus exclusion
A semaphore has permits, not ownership: acquire or tryAcquire before using a scarce resource and release exactly once in finally after successful acquisition. A CountDownLatch is one-shot; a CyclicBarrier can coordinate repeated groups of a fixed size, and a Phaser supports changing registration and multiple phases. The Phaser example uses timed interruptible waiting and forceTermination on exit; in production track registered participants and failure propagation. Prefer the simplest coordination primitive that matches the lifecycle.
Publish a message using a condition
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } }
static class Mailbox { private final ReentrantLock lock = new ReentrantLock(); private final Condition changed = lock.newCondition(); private String message; void publish(String value) throws InterruptedException, TimeoutException { if (!lock.tryLock(2, TimeUnit.SECONDS)) throw new TimeoutException(); try { message = java.util.Objects.requireNonNull(value); changed.signalAll(); } finally { lock.unlock(); } } String receive() throws InterruptedException, TimeoutException { if (!lock.tryLock(2, TimeUnit.SECONDS)) throw new TimeoutException(); try { long left = TimeUnit.SECONDS.toNanos(2); while (message == null) { if (left <= 0) throw new TimeoutException(); left = changed.awaitNanos(left); } return message; } finally { lock.unlock(); } } } public static void main(String[] args) throws Exception { Mailbox box = new Mailbox(); ThreadPoolExecutor workers = pool(1, 1); try { Future<String> reply = workers.submit(box::receive); box.publish("ready"); System.out.println(reply.get(3, TimeUnit.SECONDS)); } finally { stop(workers); } }}Expected output:
readyPublication may happen before or after the waiter arrives. The predicate under the lock makes both orders correct; the signal is not stored separately.
Limit access to a resource
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { Semaphore permits = new Semaphore(1); if (!permits.tryAcquire(0, TimeUnit.SECONDS)) throw new AssertionError(); try { System.out.println(permits.tryAcquire(0, TimeUnit.SECONDS)); } finally { permits.release(); } System.out.println(permits.availablePermits()); }}Expected output:
false1A second permit cannot be acquired while the sole permit is held. A failed acquisition must not be followed by release. This is a deterministic model of a scarce connection slot.
Coordinate a phase
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } } public static void main(String[] args) throws Exception { Phaser phase = new Phaser(2); ThreadPoolExecutor workers = pool(1, 1); try { Future<Integer> worker = workers.submit(() -> phase.awaitAdvanceInterruptibly(phase.arrive(), 3, TimeUnit.SECONDS)); int next = phase.awaitAdvanceInterruptibly(phase.arrive(), 3, TimeUnit.SECONDS); System.out.println(next); System.out.println(worker.get(3, TimeUnit.SECONDS)); } finally { phase.forceTermination(); stop(workers); } }}Expected output:
11Two registered parties arrive in phase zero. Both wait for its advancement; no subsequent phase is entered. The coordinator terminates the phaser in finally.
Common mistakes
Do not unlock a lock you failed to acquire, call Condition.await without holding its associated lock, replace a predicate loop with if, or release a semaphore permit after a failed acquisition. Avoid lock upgrades and inconsistent multi-lock ordering.
Practice
Acquire one of two semaphore permits, acquire a second, verify a third attempt fails, then release exactly the two acquired permits. Print the remaining permit count.
Expected output:
false2Compare your answer with the manual practice criteria.
Official reading: Condition · Concurrency package. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Locks and conditions — knowledge check
Original concurrency questions. Java 21-compatible scope.
When should unlock be called?
Why use a while loop around condition waiting?
What should happen after tryAcquire returns false?
Which coordinator supports dynamically registered parties?
What should a read-lock holder do before taking a write lock with ReentrantReadWriteLock?