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 synchronized keyword acquires an object's monitor on entry and releases it on exit, so only one thread at a time runs code guarded by the same monitor. Leaving the block in any way, including by an exception, releases it. The compiler implements a synchronized block with the bytecodes monitorenter and monitorexit, plus an exception handler that guarantees the exit; a synchronized method is just marked with a flag.

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(), does the JVM inflate the lock into a full monitor structure with a queue of blocked threads. Biased locking, an older optimization for locks used by one thread only, was disabled by default in Java 15 (JEP 374) and later removed, so the uncontended cost is now a single atomic instruction.

synchronized gives two guarantees: mutual exclusion, and visibility, because releasing a monitor happens-before every later acquisition of the same monitor. volatile gives only visibility and ordering, for single reads and writes of one field, without any locking. The Java Memory Model page shows both rules failing and working; this page is about using the keywords correctly.

What each form locks, and what volatile provides
FormSinceLocks or guaranteesBest for
synchronized instance methodJava 1.0The monitor of thisSmall classes whose whole state is guarded by the object itself
static synchronized methodJava 1.0The monitor of the Class objectStatic state
synchronized (obj) { } blockJava 1.0The monitor of objGuarding only part of a method, with a private lock object
wait, notify, notifyAllJava 1.0Waiting for a condition while holding the monitorGuarded waits in low-level code
volatile fieldJava 1.0, memory semantics fixed in Java 5Visibility and ordering of single reads and writesFlags, 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 method and the other through a block that locks a private object, which looks equivalent but is not. Each thread does a million increments, so every total should be 2,000,000.

Java
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):

Output
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
  • count lost updates even though both paths were "synchronized". The method locked this and the block locked lock: 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.
  • staticCount reached exactly 2,000,000: both threads used static synchronized, which always locks SyncForms.class. Note that a static synchronized method and an instance synchronized method of the same class do not exclude each other either.
  • addOnce holds the lock across both the contains check and the add, so each entry appears once. Making each list call thread-safe on its own, as Collections.synchronizedList does, would not be enough: another thread could add the entry between the check and the add.
  • The monitor is reentrant: the nested block on the same object did not deadlock, and Thread.holdsLock confirmed ownership. After an exception escaped the block, the monitor was released automatically, which explicit Lock objects only do if you write unlock() in 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.

Java
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:

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
  1. Two unrelated classes each declared a private LOCK = "LOCK". String literals are interned, so both fields refer to the same object, and the audit thread was BLOCKED while the cache held "its own" lock. Boxed values from Integer.valueOf and Boolean.TRUE are shared the same way. Since Java 16 (JEP 390), javac -Xlint:synchronization warns about synchronizing on such value-based classes. Use private final Object lock = new Object().
  2. 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 mutable with a new object, and the second thread locked that new object. A lock field must be final; never synchronize on a field you assign.

Locking on this has a milder version of the first problem: any code holding a reference to your object can lock it too, and can block your methods by accident. A private final lock object keeps the locking policy inside the class.

Waiting for a condition: wait and notify

A thread that holds a monitor can wait for some condition to become true with wait(), which releases the monitor while waiting and takes it back before returning. Another thread changes the state and calls notifyAll(). The program builds a one-slot mailbox that way and sends five messages through it, then shows two rules that are easy to break.

Java
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:

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 send waited until the receiver had emptied the slot, and each receive waited until a message was there.
  • wait() is always inside a while 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 the Object.wait Javadoc explicitly allows.
  • notifyAll() wakes every waiter, and each re-checks its condition. notify() wakes one arbitrary waiter, which can be the wrong kind (a sender when a receiver is needed), and the program can stall. Use notify only when all waiters wait for the same condition and any one of them can proceed.
  • Calling notify without holding the monitor throws IllegalMonitorStateException; the same goes for wait.
  • A notification is not stored. The notifyAll sent when nobody was waiting was lost, and the later wait(200) waited the full 200 ms. That is why waiting must depend on a state variable checked under the lock, never on the notification alone.

For new code, BlockingQueue, CountDownLatch or a Condition from ReentrantLock are easier to get right.

What volatile is for, and what it is not

A volatile field is the cheapest correct way to share a value between threads, but only for jobs that need a single read or a single write. The program shows the two classic uses and a classic misuse.

Java
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:

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
  1. A status flag: main wrote running = false once, and the looping worker saw it and stopped. Without volatile, the JIT may read the field once and loop forever, as the memory model page demonstrates.
  2. 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.
  3. The misuse: two threads checked initialized, both saw false, and the one-time setup ran 2 times. Each read and write was visible, but check-then-act is two steps, and volatile does not make them one. Use AtomicBoolean.compareAndSet(false, true), a lock, or the class-holder idiom.

Two more limits are worth knowing. count++ on a volatile field is also a read followed by a write, and loses updates. And declaring an array field volatile makes only the reference volatile, not the elements; use AtomicIntegerArray or similar for per-element visibility. Double-checked locking, which needs volatile to be correct, is covered on the Java Memory Model page.

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.

Java
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:

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
  • ThreadMXBean.findDeadlockedThreads() found 2 threads, each BLOCKED on a monitor held by the other. A thread dump from jstack PID or jcmd PID Thread.print 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.
  • 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 ReentrantLock.tryLock with a timeout when no order can be defined; see locks and conditions.

Choosing between synchronized, volatile and the alternatives

Which mechanism to use
SituationUse
Several fields that must change togethersynchronized on a private final lock object
A flag set by one thread and read by othersvolatile boolean
Replacing a configuration or snapshotvolatile reference to an immutable object
A counter or a one-time switchAtomicInteger, AtomicBoolean
Waiting until a condition holdsA BlockingQueue or latch; wait in a while loop with notifyAll in low-level code
Timeouts, interruptible waits, several conditionsReentrantLock
Lazily created singletonHolder class idiom, or volatile with double-checked locking
Two or more locks needed at onceA fixed global lock order

Before Java 24, a virtual thread that blocked while inside synchronized pinned its carrier thread; JEP 491 in Java 24 removed that restriction. See virtual threads and thread basics.