Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
kvi5hnuCode Sprout team member13 min readOn this page
A lock keeps threads out of a critical section while another thread is inside. Often, though, a thread gets into the critical section and finds that it can't proceed yet: the account doesn't have enough money, the buffer is full, the queue is empty. It has to wait until another thread changes the state. That's the job of condition objects. This article covers explicit Conditions first, then Java's built-in version: every object's intrinsic lock with synchronized, wait and notifyAll.
The problem: waiting inside a lock
Suppose the bank shouldn't transfer money that isn't there. Checking first and then transferring is a race:
if (bank.getBalance(from) >= amount)
// another thread may withdraw right here
bank.transfer(from, to, amount);
So the test and the transfer must happen inside the same lock:
bankLock.lock();
try {
while (accounts[from] < amount) {
// wait ... but how?
}
// transfer funds
} finally {
bankLock.unlock();
}
If the funds are short, the thread must wait for another thread to add money. But this thread holds the lock, so no other thread can get in to make a deposit. Waiting while holding the lock would block everyone forever.
Condition objects
A lock can have one or more associated condition objects (historically called condition variables). You create one with newCondition() and give it a name that describes the condition it represents:
private final Lock bankLock = new ReentrantLock();
private final Condition sufficientFunds = bankLock.newCondition();
When transfer finds the funds short, it calls
sufficientFunds.await();
await does two things atomically. It releases the lock and deactivates the thread, placing it in the condition's wait set. Now other threads can acquire the lock and, with luck, add money.
A thread in a wait set is different from a thread waiting to acquire the lock. When the lock becomes free, a waiting-in-await thread does not become runnable. It stays put until some other thread calls signalAll on the same condition:
sufficientFunds.signalAll();
That moves all threads from the wait set back to competing for the lock. When one of them reacquires it, its await call returns and it continues where it left off.

Always await in a loop
signalAll doesn't promise that the condition is now true. It only says it might be, check again. Another thread may also have gotten in first and used up the money. So the test must be repeated after every wake-up:
while (!(okToProceed))
condition.await();
Never use if here. The loop also protects against spurious wakeups, which the specification allows: await and wait may occasionally return without any signal at all.
When to signal
Every waiting thread depends on some other thread to wake it up. If nobody ever calls signalAll, the waiters sleep forever. If the last active thread also calls await, the whole program hangs. The rule of thumb: call signalAll whenever the object's state changes in a way that could help waiting threads. For the bank, that means after every completed transfer:
public void transfer(int from, int to, long amount) throws InterruptedException {
bankLock.lock();
try {
while (accounts[from] < amount)
sufficientFunds.await();
accounts[from] -= amount;
accounts[to] += amount;
sufficientFunds.signalAll();
} finally {
bankLock.unlock();
}
}
signalAll doesn't hand over the lock immediately. The awakened threads have to wait until the signalling thread unlocks. You can call await, signal and signalAll only while holding the condition's lock; otherwise they throw IllegalMonitorStateException. Locking costs a little speed, which is the price of correctness: the total stays fixed, and no account ever goes negative.
signal versus signalAll
signal() wakes one arbitrary waiting thread. That's cheaper, but dangerous. If the chosen thread still can't proceed, it goes back to waiting. If nothing signals again, every thread may end up waiting and the system deadlocks. In the bank, waking the wrong account's thread can do exactly that. Use signal only when any waiter can make progress after the state change, for example when each waiter consumes one item and exactly one item was added. The bounded buffer in the demo uses signal for that reason, with two separate conditions, notFull and notEmpty, so producers and consumers never wake each other by mistake.
To summarize locks and conditions:
- A lock protects sections of code, allowing only one thread to execute them at a time.
- A lock manages threads trying to enter a critical section.
- A lock can have one or more associated condition objects.
- Each condition manages threads that have entered the critical section but can't proceed.
The synchronized keyword
Explicit Lock and Condition objects give you a lot of control, but you often don't need it. Since Java 1.0, every object has an intrinsic lock with a single intrinsic condition. A method declared synchronized is protected by the intrinsic lock of this:
public synchronized void method() {
method body
}
is equivalent to
public void method() {
this.intrinsicLock.lock();
try {
method body
} finally {
this.intrinsicLock.unlock();
}
}
The intrinsic condition is used with three final methods of Object. wait() adds the thread to the wait set, which is the equivalent of await(). notifyAll() wakes all waiters, like signalAll(), and notify() wakes one, like signal(). The Condition methods had to be named await, signalAll and signal because every object, including every Condition, already has wait and notify methods.
With synchronized, the bank shrinks to:
class Bank {
private final long[] accounts;
public synchronized void transfer(int from, int to, long amount) throws InterruptedException {
while (accounts[from] < amount)
wait(); // wait on the intrinsic lock's condition
accounts[from] -= amount;
accounts[to] += amount;
notifyAll(); // wake all threads waiting on this object
}
public synchronized long getTotalBalance() { ... }
}
That's much shorter. To read it, you have to know that each object has a lock that manages threads entering its synchronized methods, and one condition that manages threads that called wait. The same rules apply: call wait/notify/notifyAll only while holding the lock, which means inside a synchronized method or block. Otherwise you get IllegalMonitorStateException. And always call wait inside a loop.
Static synchronized methods lock the intrinsic lock of the Class object. A static synchronized method of Bank locks Bank.class, so no other thread can run any static synchronized method of Bank at the same time.
Limitations of intrinsic locks
- You can't interrupt a thread that is waiting to acquire an intrinsic lock (
ReentrantLockhaslockInterruptibly). - You can't time out while trying to acquire it (
ReentrantLockhastryLock(time, unit)). - There is only one condition per lock, so unrelated waiters all wake together.
- With virtual threads in Java 21 to 23, a thread holding or waiting for an intrinsic lock is pinned to its carrier. If it blocks while pinned, throughput suffers or the carrier pool starves. On those versions,
-Djdk.tracePinnedThreads=fullor JFRjdk.VirtualThreadPinnedevents reveal where. Java 24 dropped the system property, but the JFR event remains. Java 24 (JEP 491) lets virtual threads unmount insidesynchronized, which removes most pinning.
What should you use?
- Preferably neither. The
java.util.concurrentpackage has higher-level tools that do the locking for you: blocking queues, concurrent maps, atomics and executors. A producer–consumer design with aBlockingQueue(article 100) needs no explicit locks at all. - If
synchronizedfits, use it. It is less code and harder to get wrong, since you can't forget to unlock. But remember that the lock is public (see below). - Use
Lock/Conditionwhen you need whatsynchronizedcan't do: multiple conditions, timeouts, interruptible waiting, or fairness. On Java 21 to 23 with virtual threads, also prefer them around blocking work.
Synchronized blocks
You can also lock an object's intrinsic lock for just a block of code:
synchronized (obj) {
critical section
}
A common pattern is a private ad-hoc lock object that exists only for its lock:
public class Bank {
private final long[] accounts;
private final Object lock = new Object();
public void transfer(int from, int to, long amount) {
synchronized (lock) {
accounts[from] -= amount;
accounts[to] += amount;
}
log(...); // outside the lock: keep critical sections short
}
}
A private lock object also fixes the "public lock" problem of synchronized methods. Since anyone can write synchronized (yourBank) { … }, outside code can hold your lock and stall or deadlock your methods. Nobody else can lock a private object.
Client-side locking
Sometimes code borrows another object's lock to make a sequence of calls atomic. That's called client-side locking. Even though each Vector method is synchronized, this transfer isn't atomic, because a thread can be preempted between the get and the set:
accounts.set(from, accounts.get(from) - amount); // not atomic as a whole
Wrapping the sequence in synchronized (accounts) { … } works only because Vector happens to use its own intrinsic lock for all its methods. Its documentation doesn't promise that, so client-side locking is fragile and not recommended. Prefer classes that offer the compound operation you need, such as ConcurrentHashMap.merge, or use your own lock around your own data.
The JVM has built-in support for synchronized methods (an access flag). Synchronized blocks compile to explicit monitorenter/monitorexit bytecodes, plus exception handling that guarantees the exit.
The monitor concept
Locks and conditions are powerful but not very object-oriented. In the 1970s, Per Brinch Hansen and Tony Hoare proposed the monitor, which makes safe concurrency a property of a class:
- A monitor is a class with only private fields.
- Each object has an associated lock.
- All methods are locked by that lock automatically, so no thread can touch the fields while another thread is inside a method.
- The lock can have any number of associated conditions.
Java adopted this loosely. Every object has an intrinsic lock and condition, and synchronized methods act like monitor methods. But Java doesn't require fields to be private or methods to be synchronized, and it exposes the lock to clients. Brinch Hansen was scathing about this in a 1999 paper titled "Java's Insecure Parallelism", arguing that Java had ignored the safety that made monitors worthwhile. The practical lesson is to follow the monitor discipline yourself: keep shared state private, guard every access with the same lock, and don't let callers lock your objects.
A complete example
The demo shows a transfer that waits on a Condition until a deposit arrives, the same thing with synchronized/wait/notifyAll, a bounded buffer with two conditions passing 1,000 numbers from a producer to a consumer, a static synchronized counter, the IllegalMonitorStateException you get from waiting or signalling without the lock, the lock-object pitfalls, and client-side locking on a Vector.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class Solution {
// 1. Lock + Condition: transfers wait until the source account has enough money
static class Bank {
private final long[] accounts;
private final Lock bankLock = new ReentrantLock();
private final Condition sufficientFunds = bankLock.newCondition();
Bank(long... balances) { accounts = balances.clone(); }
void transfer(int from, int to, long amount) throws InterruptedException {
bankLock.lock();
try {
while (accounts[from] < amount) // always re-test in a loop
sufficientFunds.await(); // releases the lock while waiting
accounts[from] -= amount;
accounts[to] += amount;
sufficientFunds.signalAll(); // balances changed: let waiters re-check
} finally {
bankLock.unlock();
}
}
long balance(int i) {
bankLock.lock();
try { return accounts[i]; } finally { bankLock.unlock(); }
}
}
// 2. the same bank with synchronized, wait and notifyAll
static class SyncBank {
private final long[] accounts;
SyncBank(long... balances) { accounts = balances.clone(); }
synchronized void transfer(int from, int to, long amount) throws InterruptedException {
while (accounts[from] < amount) wait(); // waits on this object's intrinsic condition
accounts[from] -= amount;
accounts[to] += amount;
notifyAll();
}
synchronized long total() { long s = 0; for (long a : accounts) s += a; return s; }
}
// 3. a bounded buffer with two conditions
static class BoundedBuffer<E> {
private final Object[] items;
private int head, tail, count;
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
BoundedBuffer(int capacity) { items = new Object[capacity]; }
void put(E e) throws InterruptedException {
lock.lock();
try {
while (count == items.length) notFull.await();
items[tail] = e;
tail = (tail + 1) % items.length;
count++;
notEmpty.signal(); // one waiting consumer suffices: each takes one item
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
E take() throws InterruptedException {
lock.lock();
try {
while (count == 0) notEmpty.await();
E e = (E) items[head];
items[head] = null;
head = (head + 1) % items.length;
count--;
notFull.signal();
return e;
} finally {
lock.unlock();
}
}
}
// 4. synchronized static methods lock the Class object
static int instances;
static synchronized void register() { instances++; }
static class Base {
void lockedOnGetClass(List<String> log) {
synchronized (getClass()) { log.add("locked " + getClass().getSimpleName() + ".class"); }
}
}
static class Derived extends Base { }
public static void main(String[] args) throws Exception {
// a transfer that must wait for a deposit
var bank = new Bank(100, 1_000);
Thread waiter = Thread.ofPlatform().start(() -> {
try { bank.transfer(0, 1, 300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
while (waiter.getState() != Thread.State.WAITING) Thread.sleep(1);
System.out.println("transfer of 300 from account 0 (balance " + bank.balance(0) + ") is " + waiter.getState());
bank.transfer(1, 0, 250); // signalAll wakes the waiter
waiter.join();
System.out.println("after a deposit of 250: account 0 = " + bank.balance(0) + ", account 1 = " + bank.balance(1));
// the synchronized version behaves the same way
var syncBank = new SyncBank(100, 1_000);
Thread syncWaiter = Thread.ofPlatform().start(() -> {
try { syncBank.transfer(0, 1, 300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
while (syncWaiter.getState() != Thread.State.WAITING) Thread.sleep(1);
System.out.println("synchronized transfer is " + syncWaiter.getState() + " in wait()");
syncBank.transfer(1, 0, 250); // notifyAll wakes it
syncWaiter.join();
System.out.println("synchronized bank total " + syncBank.total() + ", waiter finished: " + !syncWaiter.isAlive());
// producer and consumer through the bounded buffer
var buffer = new BoundedBuffer<Integer>(5);
long[] sum = new long[1];
Thread consumer = Thread.ofPlatform().start(() -> {
try {
for (int i = 0; i < 1_000; i++) sum[0] += buffer.take();
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
for (int i = 1; i <= 1_000; i++) buffer.put(i);
consumer.join();
System.out.println("consumer received sum " + sum[0] + " (expected 500500)");
// static synchronized: one lock for the whole class
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int i = 0; i < 10_000; i++) pool.submit(Solution::register);
}
System.out.println("static synchronized counter " + instances);
// wait/notify require the lock
var obj = new Object();
try {
obj.wait();
} catch (IllegalMonitorStateException e) {
System.out.println("wait() without holding the lock: IllegalMonitorStateException");
}
try {
bank.sufficientFunds.signalAll();
} catch (IllegalMonitorStateException e) {
System.out.println("signalAll() without holding the lock: IllegalMonitorStateException");
}
// bad lock objects
String lockA = "LOCK";
String lockB = "LOCK";
System.out.println("two string-literal locks are the same object: " + (lockA == lockB));
var log = new ArrayList<String>();
new Base().lockedOnGetClass(log);
new Derived().lockedOnGetClass(log);
System.out.println("synchronized (getClass()) uses different locks: " + log);
// client-side locking on a synchronized Vector
var accounts = new Vector<>(List.of(500L, 500L));
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
for (int t = 0; t < 4; t++)
pool.submit(() -> {
for (int i = 0; i < 10_000; i++)
synchronized (accounts) { // relies on Vector locking itself: fragile
accounts.set(0, accounts.get(0) - 1);
accounts.set(1, accounts.get(1) + 1);
}
});
}
System.out.println("client-side locked Vector " + accounts + ", total " + (accounts.get(0) + accounts.get(1)));
}
}
transfer of 300 from account 0 (balance 100) is WAITING
after a deposit of 250: account 0 = 50, account 1 = 1050
synchronized transfer is WAITING in wait()
synchronized bank total 1100, waiter finished: true
consumer received sum 500500 (expected 500500)
static synchronized counter 10000
wait() without holding the lock: IllegalMonitorStateException
signalAll() without holding the lock: IllegalMonitorStateException
two string-literal locks are the same object: true
synchronized (getClass()) uses different locks: [locked Base.class, locked Derived.class]
client-side locked Vector [-39500, 40500], total 1000
Common questions
Why must await or wait always be called in a loop?
A wake-up only means the condition might have changed. Another thread may have used up the resource first, and spurious wakeups can happen without any signal. Re-test the condition every time the thread wakes.
What happens if I call wait() outside a synchronized block?
It throws IllegalMonitorStateException. You must hold the object's intrinsic lock to call wait, notify or notifyAll. Similarly, await and signal require holding the Condition's lock.
Should I use notify or notifyAll?
Use notifyAll (or signalAll) unless every waiting thread waits for the same condition and any one of them can make progress. Waking a single thread that can't proceed can leave the whole program waiting.
What does a static synchronized method lock?
The Class object of the class, such as Bank.class. It doesn't lock any instance, so a static and an instance synchronized method of the same class can run at the same time.
Why is it a bad idea to lock on a string or Integer?
String literals are interned, and small Integer values are cached, so unrelated code may end up sharing the same lock object. Lock on a private final Object lock = new Object() that only your class can see.
API reference
java.util.concurrent.locks.Lock and Condition
| Method | Description |
|---|---|
Condition newCondition() (Lock) | a new condition object tied to this lock |
void await() | releases the lock, waits in this condition's wait set, reacquires the lock before returning |
boolean await(long time, TimeUnit unit), long awaitNanos(long n), void awaitUninterruptibly() | timed and uninterruptible variants |
void signalAll() | moves all waiting threads back to competing for the lock |
void signal() | wakes one arbitrary waiting thread |
java.lang.Object
| Method | Description |
|---|---|
void wait() | waits until notified; only while holding this object's lock, otherwise IllegalMonitorStateException |
void wait(long millis), void wait(long millis, int nanos) | waits until notified or the time elapses (nanos below 1,000,000) |
void notifyAll() | wakes all threads waiting on this object; requires the lock |
void notify() | wakes one arbitrary waiting thread; requires the lock |
Summary
- A condition object manages threads that hold the lock but can't proceed.
awaitreleases the lock and waits, andsignalAlllets waiters compete for the lock again. - Always re-test the condition in a
whileloop aroundawaitorwait. Signal whenever the state changes in a way that could help waiters, and prefersignalAllunless any single waiter can make progress. - Every object has an intrinsic lock and condition.
synchronizedmethods and blocks use the lock, andwait/notifyAll/notifyuse the condition. Static synchronized methods lock theClassobject. - Prefer high-level concurrency utilities. Use
synchronizedwhen it suffices, andLock/Conditionfor timeouts, interruptibility, multiple conditions or virtual-thread workloads on Java 21 to 23. - Lock on private, dedicated objects. Never use string literals, boxed values or
getClass(), and avoid client-side locking.
Practice Questions
Why must await be called in a while loop rather than an if statement?
After waking, the condition may still be false. Another thread may have acted first, signalAll only says "maybe", and spurious wakeups are allowed. The loop re-tests the condition and waits again if necessary.
What is the difference between a thread blocked in lock() and a thread in await()?
A thread in lock() becomes runnable as soon as the lock is available. A thread in await() has released the lock and sits in the condition's wait set. It doesn't compete for the lock again until another thread calls signal or signalAll on that condition, or until it times out.
What happens if you call notifyAll() on an object without holding its lock?
It throws IllegalMonitorStateException. wait, notify and notifyAll may only be called by the thread that owns the object's intrinsic lock, that is, inside a synchronized method or block on that object.
Why is synchronized (getClass()) a bad way to protect a static counter?
In a subclass, getClass() returns the subclass's Class object, so code running in different classes locks different objects and the counter is no longer protected. Use synchronized (MyClass.class).
Give two things ReentrantLock can do that synchronized cannot.
Any two of: give up waiting after a timeout (tryLock(time, unit)), respond to interrupts while waiting (lockInterruptibly), provide several condition objects per lock, offer fair ordering, or query its state (isLocked, getHoldCount, getQueueLength).
Previous: Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Next: Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Related reading
- Java Race Conditions and ReentrantLock: Synchronizing Shared Data
- Java Callable, Future and ExecutorService: Thread Pools and Task Results
- Java Virtual Threads, Interrupts and Daemon Threads: Thread Properties Explained
- Java Thread States: New, Runnable, Blocked, Waiting and Terminated
- Java Threads: Creating and Running Threads with Runnable and Thread

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Java Callable, Future and ExecutorService: Thread Pools and Task Results
Run tasks that return results with Callable and Future, then let an ExecutorService manage threads: fixed, cached and single-thread pools, virtual-thread-per-task executors, get with timeouts, cancellation, Future.state and resultNow, closing executors, and throttling with semaphores.
Discussion
Sign in to ask a question or share what you learned.