synchronized and volatile
synchronized gives one thread at a time exclusive access to a block of code and makes its changes visible to the next thread that enters. volatile makes single reads and writes visible without locking. This page explains how monitors work in the JVM, shows what each form of synchronized actually locks, the lock objects that silently break exclusion, guarded waits with wait and notify, the jobs volatile is right for, and a deadlock caught in the act.
Contents
Monitors and the two keywords
Every Java object can act as a lock, called its monitor. The synchronizedsynchronizedmonitorentermonitorexitsynchronized
HotSpot does not create a heavyweight lock for every object. An uncontended lock is taken by a compare-and-set on the object's header word. Only when threads actually compete, or when a thread calls wait()
synchronizedvolatile
| Form | Since | Locks or guarantees | Best for |
|---|---|---|---|
synchronized | Java 1.0 | The monitor of this | Small classes whose whole state is guarded by the object itself |
static synchronized | Java 1.0 | The monitor of the Class | Static state |
synchronized (obj) { } | Java 1.0 | The monitor of obj | Guarding only part of a method, with a private lock object |
waitnotifynotifyAll | Java 1.0 | Waiting for a condition while holding the monitor | Guarded waits in low-level code |
volatile | Java 1.0, memory semantics fixed in Java 5 | Visibility and ordering of single reads and writes | Flags, and publishing immutable objects |
The programs here were compiled and run on JDK 21.
What each form of synchronized locks
A class has an instance counter, a static counter and a list of log entries. One thread increments the instance counter through a synchronized
import java.util.ArrayList;
import java.util.List;
public class SyncForms {
private int count;
private final Object lock = new Object();
private static int staticCount;
private final List<String> log = new ArrayList<>();
synchronized void incrementMethod() { // locks 'this'
count++;
}
void incrementBlock() {
synchronized (lock) { // locks a private object: nobody else can
count++;
}
}
static synchronized void incrementStatic() { // locks SyncForms.class
staticCount++;
}
// Check-then-act must be atomic as a whole, not per call
void addOnce(String entry) {
synchronized (log) {
if (!log.contains(entry)) {
log.add(entry);
}
}
}
public static void main(String[] args) throws InterruptedException {
SyncForms s = new SyncForms();
// One thread uses the synchronized method, the other the synchronized block
Thread a = new Thread(() -> {
for (int i = 0; i < 1000000; i++) {
s.incrementMethod();
incrementStatic();
s.addOnce("entry-" + (i % 3));
}
});
Thread b = new Thread(() -> {
for (int i = 0; i < 1000000; i++) {
s.incrementBlock();
incrementStatic();
s.addOnce("entry-" + (i % 3));
}
});
a.start();
b.start();
a.join();
b.join();
System.out.println("count = " + s.count + " (expected 2000000, varies, see below)");
System.out.println("staticCount = " + staticCount + " (expected 2000000)");
System.out.println("log = " + s.log + " (each entry once)");
// Reentrant: a thread can enter a monitor it already holds
synchronized (s) {
synchronized (s) {
System.out.println("nested synchronized on the same object, holdsLock = "
+ Thread.holdsLock(s));
}
}
// An exception leaves the block and releases the monitor automatically
try {
synchronized (s) {
throw new IllegalStateException("boom");
}
} catch (IllegalStateException e) {
System.out.println("after an exception inside synchronized, holdsLock = "
+ Thread.holdsLock(s));
}
}
}
Output (the first count is different every run):
count = 1999969 (expected 2000000, varies, see below)
staticCount = 2000000 (expected 2000000)
log = [entry-0, entry-1, entry-2] (each entry once)
nested synchronized on the same object, holdsLock = true
after an exception inside synchronized, holdsLock = false
lost updates even though both paths were "synchronized". The method lockedcount and the block lockedthis : two different monitors, so the two threads never excluded each other. All code that touches a piece of state must use the same lock, which is why it helps to document which lock guards which field.lock reached exactly 2,000,000: both threads usedstaticCount , which always locksstatic synchronized . Note that a static synchronized method and an instance synchronized method of the same class do not exclude each other either.SyncForms.class holds the lock across both theaddOnce check and thecontains , so each entry appears once. Making each list call thread-safe on its own, asadd does, would not be enough: another thread could add the entry between the check and the add.Collections.synchronizedList- The monitor is reentrant: the nested block on the same object did not deadlock, and
confirmed ownership. After an exception escaped the block, the monitor was released automatically, which explicitThread.holdsLock objects only do if you writeLock inunlock() .finally
Lock-object traps
The object you lock decides who you exclude, and two choices quietly break that. The program shows a lock that is shared by accident and a lock that changes while it is held. Latches hold the threads in position, so the outcome is the same on every run.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class LockObjectTraps {
// Two unrelated classes that each think they have a private lock
static class Cache {
private static final String LOCK = "LOCK"; // a string literal...
}
static class Audit {
private static final String LOCK = "LOCK"; // ...is the same interned object
}
private static Object mutable = new Object();
public static void main(String[] args) throws InterruptedException {
// Trap 1: string literals are interned, so both classes share one monitor
System.out.println("1. same object: " + (Cache.LOCK == Audit.LOCK));
CountDownLatch held = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Thread cache = new Thread(() -> {
synchronized (Cache.LOCK) {
held.countDown();
await(release);
}
});
cache.start();
held.await();
Thread audit = new Thread(() -> {
synchronized (Audit.LOCK) {
System.out.println("1. audit finally got its lock");
}
});
audit.start();
Thread.sleep(100);
System.out.println("1. audit thread state while cache holds 'its' lock: "
+ audit.getState());
release.countDown();
cache.join();
audit.join();
// Trap 2: replacing the lock object inside the block lets a second thread in
AtomicInteger inside = new AtomicInteger();
AtomicInteger maxInside = new AtomicInteger();
CountDownLatch bothIn = new CountDownLatch(2);
Runnable task = () -> {
synchronized (mutable) {
mutable = new Object(); // the next thread locks this one
maxInside.accumulateAndGet(inside.incrementAndGet(), Math::max);
bothIn.countDown();
await(bothIn); // wait until both are inside
inside.decrementAndGet();
}
};
Thread a = new Thread(task);
Thread b = new Thread(task);
a.start();
Thread.sleep(50);
b.start();
a.join();
b.join();
System.out.println("2. threads inside the 'exclusive' block at once: " + maxInside.get());
}
static void await(CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output:
1. same object: true
1. audit thread state while cache holds 'its' lock: BLOCKED
1. audit finally got its lock
2. threads inside the 'exclusive' block at once: 2
- Two unrelated classes each declared a private
. String literals are interned, so both fields refer to the same object, and the audit thread wasLOCK = "LOCK" while the cache held "its own" lock. Boxed values fromBLOCKED andInteger.valueOf are shared the same way. Since Java 16 (JEP 390),Boolean.TRUE warns about synchronizing on such value-based classes. Usejavac -Xlint:synchronization .private final Object lock = new Object() - The second thread entered the "exclusive" block while the first was still inside, so 2 threads were in it at once. The first thread had replaced
with a new object, and the second thread locked that new object. A lock field must bemutable ; never synchronize on a field you assign.final
Locking on this
Waiting for a condition: wait and notify
A thread that holds a monitor can wait for some condition to become true with wait()notifyAll()
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class WaitNotify {
// A one-slot mailbox built from a monitor: the classic guarded wait
static class Mailbox {
private final Deque<String> slot = new ArrayDeque<>();
synchronized void send(String message) throws InterruptedException {
while (!slot.isEmpty()) { // guard: wait until there is room
wait(); // releases the monitor while waiting
}
slot.add(message);
notifyAll(); // wake receivers (and any waiting senders)
}
synchronized String receive() throws InterruptedException {
while (slot.isEmpty()) { // while, never if
wait();
}
String m = slot.remove();
notifyAll();
return m;
}
}
public static void main(String[] args) throws InterruptedException {
Mailbox box = new Mailbox();
List<String> received = new ArrayList<>();
Thread receiver = new Thread(() -> {
try {
for (int i = 0; i < 5; i++) {
received.add(box.receive());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
receiver.start();
for (int i = 1; i <= 5; i++) {
box.send("msg-" + i); // blocks until the previous one was taken
}
receiver.join();
System.out.println("received in order: " + received);
// wait() and notify() need the monitor of the object they are called on
Object lock = new Object();
try {
lock.notify();
} catch (IllegalMonitorStateException e) {
System.out.println("notify() without the monitor: IllegalMonitorStateException");
}
// A notify sent before anyone waits is lost; the guard condition is what saves you
synchronized (lock) {
lock.notifyAll(); // nobody waiting: this does nothing
}
long t0 = System.nanoTime();
synchronized (lock) {
lock.wait(200); // so this waits the full timeout
}
System.out.println("wait after an earlier notify returned after ~"
+ (System.nanoTime() - t0) / 100000000 * 100 + " ms: the signal was lost");
}
}
Output:
received in order: [msg-1, msg-2, msg-3, msg-4, msg-5]
notify() without the monitor: IllegalMonitorStateException
wait after an earlier notify returned after ~200 ms: the signal was lost
- All five messages arrived in order. Each
waited until the receiver had emptied the slot, and eachsend waited until a message was there.receive is always inside await() loop that re-checks the condition. A thread can wake up because of a notification meant for another kind of waiter (here, senders and receivers share one monitor), because the state changed again before it got the monitor back, or spuriously, which thewhile Javadoc explicitly allows.Object.wait wakes every waiter, and each re-checks its condition.notifyAll() wakes one arbitrary waiter, which can be the wrong kind (a sender when a receiver is needed), and the program can stall. Usenotify() only when all waiters wait for the same condition and any one of them can proceed.notify- Calling
without holding the monitor throwsnotify ; the same goes forIllegalMonitorStateException .wait - A notification is not stored. The
sent when nobody was waiting was lost, and the laternotifyAll waited the full 200 ms. That is why waiting must depend on a state variable checked under the lock, never on the notification alone.wait(200)
For new code, Condition
What volatile is for, and what it is not
A volatile
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileUses {
// 1. A status flag: one writer, any number of readers
static volatile boolean running = true;
// 2. Publishing an immutable snapshot: readers always see a complete object
record Config(String url, int timeoutMs, List<String> hosts) { }
static volatile Config config = new Config("db://a", 1000, List.of("h1"));
// 3. The trap: check-then-act on a volatile is not atomic
static volatile boolean initialized;
static final AtomicInteger INIT_RUNS = new AtomicInteger();
static void initOnce(CountDownLatch go) {
await(go);
if (!initialized) { // both threads can pass this check...
sleep(50);
INIT_RUNS.incrementAndGet(); // ...and both run the "one-time" setup
initialized = true;
}
}
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long loops = 0;
while (running) {
loops++;
}
System.out.println("1. worker saw running=false and stopped (looped: " + (loops > 0)
+ ")");
});
worker.start();
Thread.sleep(100);
running = false;
worker.join();
Thread reader = new Thread(() -> {
Config c = config; // read the reference once, then use the copy
System.out.println("2. reader sees " + c.url() + ", " + c.timeoutMs() + " ms, "
+ c.hosts());
});
config = new Config("db://b", 2500, List.of("h1", "h2")); // replace as a whole
reader.start();
reader.join();
CountDownLatch go = new CountDownLatch(1);
Thread i1 = new Thread(() -> initOnce(go));
Thread i2 = new Thread(() -> initOnce(go));
i1.start();
i2.start();
go.countDown();
i1.join();
i2.join();
System.out.println("3. one-time setup ran " + INIT_RUNS.get() + " times");
}
static void await(CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output:
1. worker saw running=false and stopped (looped: true)
2. reader sees db://b, 2500 ms, [h1, h2]
3. one-time setup ran 2 times
- A status flag:
wrotemain once, and the looping worker saw it and stopped. Withoutrunning = false , the JIT may read the field once and loop forever, as thevolatilememory model page demonstrates. - Publishing a snapshot: the whole configuration is an immutable record, replaced by one volatile write. Any reader that reads the reference sees a complete object, never a URL from one version and hosts from another. Readers should read the field once into a local variable, as the reader does, so that all their uses refer to the same snapshot.
- The misuse: two threads checked
, both saw false, and the one-time setup ran 2 times. Each read and write was visible, but check-then-act is two steps, andinitialized does not make them one. Usevolatile , a lock, or the class-holder idiom.AtomicBoolean.compareAndSet(false, true)
Two more limits are worth knowing. count++volatileAtomicIntegerArrayvolatile
Deadlock: catching it and preventing it
Two threads that take two monitors in opposite orders can each hold one and wait forever for the other. The program creates exactly that situation, asks the JVM to find it, and then runs two threads that take the locks in the same order.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class DeadlockDemo {
static final Object A = new Object();
static final Object B = new Object();
static final Object C = new Object();
static final Object D = new Object();
static void lockBoth(Object first, Object second, String name) {
synchronized (first) {
sleep(100);
synchronized (second) {
System.out.println(name + " got both locks");
}
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
// Opposite lock order in two threads: each waits for the other forever
Thread t1 = new Thread(() -> lockBoth(A, B, "t1"), "worker-1");
Thread t2 = new Thread(() -> lockBoth(B, A, "t2"), "worker-2");
t1.setDaemon(true);
t2.setDaemon(true);
t1.start();
t2.start();
Thread.sleep(500);
ThreadMXBean mx = ManagementFactory.getThreadMXBean();
long[] ids = mx.findDeadlockedThreads();
System.out.println("deadlocked threads found: " + (ids == null ? 0 : ids.length));
for (var info : mx.getThreadInfo(ids)) {
System.out.println(" " + info.getThreadName() + " is " + info.getThreadState()
+ ", waiting for a lock held by " + info.getLockOwnerName());
}
// The fix: every thread takes the locks in the same global order
Thread t3 = new Thread(() -> lockBoth(C, D, "t3"), "worker-3");
Thread t4 = new Thread(() -> lockBoth(C, D, "t4"), "worker-4");
t3.start();
t4.start();
t3.join();
t4.join();
System.out.println("same lock order C then D: both threads finished");
}
}
Output:
deadlocked threads found: 2
worker-1 is BLOCKED, waiting for a lock held by worker-2
worker-2 is BLOCKED, waiting for a lock held by worker-1
t3 got both locks
t4 got both locks
same lock order C then D: both threads finished
found 2 threads, eachThreadMXBean.findDeadlockedThreads() on a monitor held by the other. A thread dump fromBLOCKED orjstack PID reports "Found one Java-level deadlock" with the same details. A thread blocked on a monitor cannot be interrupted, so nothing short of ending the JVM releases these two; they were daemon threads, which let the program end.jcmd PID Thread.print- With the locks always taken in the same order, C before D, the two threads simply took turns, and both finished. A global lock order, for example by account id, is the standard prevention.
- Other ways out are holding only one lock at a time, not calling unknown code (listeners, callbacks) while holding a lock, and
with a timeout when no order can be defined; seeReentrantLock.tryLocklocks and conditions .
Choosing between synchronized, volatile and the alternatives
| Situation | Use |
|---|---|
| Several fields that must change together | synchronized |
| A flag set by one thread and read by others | volatile boolean |
| Replacing a configuration or snapshot | volatile |
| A counter or a one-time switch | |
| Waiting until a condition holds | A BlockingQueuewaitwhilenotifyAll |
| Timeouts, interruptible waits, several conditions | |
| Lazily created singleton | Holder class idiom, or volatile |
| Two or more locks needed at once | A fixed global lock order |
Before Java 24, a virtual thread that blocked while inside synchronized