Java Reference ยท Concurrency
Java synchronized in depth: monitors and wait/notify
In-depth reference for Java monitors: how synchronized methods and blocks lock, reentrancy, wait/notify/notifyAll, spurious wakeups and what to lock on.
Every Java object has a monitor: a lock plus a wait set. The synchronized keyword acquires that monitor on entry and releases it on exit, even if an exception is thrown. Only one thread can own an object's monitor at a time, so code guarded by the same monitor runs one thread at a time, and every release makes the guarded writes visible to the next thread that acquires the monitor.
Monitors do two jobs: mutual exclusion (no two threads inside at once) and visibility (a happens-before edge between unlock and the next lock). With wait(), notify() and notifyAll() they also offer a way for threads to wait for a condition to become true. This page covers the mechanics; the keyword itself is described in synchronized.
synchronized (lock) { // acquire lock's monitor while (!ready) { lock.wait(); // release it and sleep until notified } use(data); } // release
Try it
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.
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.
Syntax
synchronized (expression) { ... } // block: locks the object the expression gives synchronized returnType method(...) { ... } // instance method: locks this static synchronized returnType method(...) { ... } // static method: locks the Class object
Method of Object |
Description |
|---|---|
wait() |
Releases the monitor and waits until notified or interrupted, then re-acquires the monitor. |
wait(long millis) |
Same, but gives up after the timeout (0 means forever). |
notify() |
Wakes one thread waiting on this object (which one is unspecified). |
notifyAll() |
Wakes all waiting threads; they compete for the monitor. |
Thread.holdsLock(Object) |
true if the current thread owns the object's monitor. |
Throws: wait, notify and notifyAll throw IllegalMonitorStateException if the caller does not own the monitor. wait throws InterruptedException. synchronized (null) throws NullPointerException.
Usage notes
- Always
wait()in awhileloop that re-checks the condition. Threads can wake up spuriously, and by the time a notified thread gets the monitor, another thread may have changed the state. - Prefer
notifyAll()unless all waiters are interchangeable and only one can proceed;notify()can wake the wrong thread and leave the right one asleep. - Lock on a private
finalobject when the lock is an implementation detail. Locking onthislets outside code interfere; never lock on strings, boxed numbers, or class literals you do not own, since they can be shared. static synchronizedand instancesynchronizeduse different locks (theClassobject vs. the instance), so they do not exclude each other.- Reentrant. The same thread can acquire the same monitor repeatedly; it is released fully only when the outermost block exits.
- Keep critical sections short and never call unknown code (callbacks, listeners) while holding a lock; that is how deadlocks start.
- Not fair. Waiting threads may be served in any order, and a thread can starve. Use
ReentrantLock(true)if fairness matters. - Virtual threads. Since Java 24 a virtual thread that blocks in a
synchronizedblock no longer pins its carrier thread. In Java 21 to 23 it did, which is a reason to preferReentrantLockin older code bases. - Not interruptible or timed-out when acquiring. A thread waiting to enter
synchronizedcannot be interrupted and has no timeout;Lock.lockInterruptibly()andtryLock()can.