Skip to content
javahacks.dev
Concurrency

Java Synchronized Blocks Monitors and Lock Contention

How synchronized uses monitors, what lock contention looks like in a thread dump, how to shrink critical sections and what changed for virtual threads.

6 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, Linux and IntelliJ IDEA logos.

synchronized is the oldest concurrency tool in Java and still the one you meet first in legacy code. It is simple: one thread at a time inside. Its costs show only under load, as contention, and its misuse shows as deadlocks. This post covers how it works, how to see contention and how to shrink it. For the alternatives, see volatile vs synchronized vs atomic.

How it works

java
class Inventory {
    private final Map<String, Integer> stock = new HashMap<>();

    synchronized void add(String sku, int n) {       // locks 'this'
        stock.merge(sku, n, Integer::sum);
    }

    boolean remove(String sku, int n) {
        synchronized (this) {                        // same lock, as a block
            int have = stock.getOrDefault(sku, 0);
            if (have < n) return false;
            stock.put(sku, have - n);
            return true;
        }
    }
}

A thread entering a synchronized region acquires the object's monitor; others that want the same monitor wait. A synchronized instance method locks this; a static synchronized method locks the Class object. The monitor is reentrant, so the same thread can enter again. Leaving the block releases it and makes the thread's writes visible to the next thread that locks, as in the memory model.

Lock on something private

java
private final Object lock = new Object();
synchronized (lock) { /* ... */ }

A private lock object means no outside code can synchronize on it and cause interference or a deadlock. Avoid synchronized (this) on a class that others use, and never lock on a String literal, a boxed Integer or a class that may be reused, because unrelated code might hold the same object.

Reading contention in a thread dump

Take a dump with jcmd <pid> Thread.print. A thread stuck on a monitor looks like:

Text
"http-nio-8080-exec-17" #58 prio=5 ... state=BLOCKED
   java.lang.Thread.State: BLOCKED (on object monitor)
	at dev.javahacks.Inventory.add(Inventory.java:7)
	- waiting to lock <0x000000076ab62208> (a dev.javahacks.Inventory)

and the owner shows - locked <0x000000076ab62208>. If dozens of threads wait for the same address, that lock is the bottleneck. Take two or three dumps to confirm it is persistent. Using jcmd and jstack safely covers the commands.

Reduce contention

TechniqueExample
Shorter critical sectionCompute outside the lock, update inside
Lock splittingSeparate locks for independent fields
Lock stripingMany locks keyed by hash, as ConcurrentHashMap does
Concurrent collectionsConcurrentHashMap, ConcurrentLinkedQueue
Immutable snapshotsCopy-on-write for read-mostly data
Remove sharingPer-thread data merged at the end
java
// Compute outside, publish inside
Report report = buildReport(data);        // slow, no lock
synchronized (lock) { latest = report; }  // fast

Never perform I/O or call overridable code inside a synchronized block. A slow database call under a lock turns every other thread into a waiter, and a callback can take another lock and deadlock.

Biased locking is gone

Older advice mentions biased locking, an optimization for uncontended locks. It was disabled by default in Java 15 and removed afterwards, so uncontended synchronized is cheap and needs no tuning.

Virtual threads and pinning

On virtual threads, a thread that blocks inside synchronized could not unmount from its carrier through Java 23, which reduced scalability if the block waited on I/O. Java 24 implemented JEP 491, which lets virtual threads release the carrier while waiting on a monitor in most cases. Pinning remains when native frames are on the stack. If you are on Java 21 to 23, use ReentrantLock for code that blocks under a lock; on 24 and later, synchronized is fine.

Measure contention with Flight Recorder

A thread dump shows contention for a moment. JFR records every time a thread waited to enter a monitor, with the duration and the stack. Start a recording and read the events afterwards:

Shell
jcmd 4242 JFR.start name=locks duration=60s filename=/tmp/locks.jfr
jfr print --events jdk.JavaMonitorEnter /tmp/locks.jfr | head -40

Each jdk.JavaMonitorEnter event names the monitor class, the thread that waited and for how long. The recording only keeps waits above a threshold, 20 ms in the default settings and 10 ms in the profile settings, so lower it to see shorter ones. Sort the events by duration and group by the monitor class. A single class that accounts for most of the total waiting time is the place to work. Mission Control shows the same data with a lock instances view.

Shrink the critical section

The most effective change is moving work out of the synchronized block. A block that does a computation and a write holds the lock for both:

java
// before: the lock is held while the price is computed
synchronized (this) {
    BigDecimal price = pricing.compute(order);     // slow
    totals.merge(order.customer(), price, BigDecimal::add);
}

// after: compute outside, lock only for the shared update
BigDecimal price = pricing.compute(order);
synchronized (this) {
    totals.merge(order.customer(), price, BigDecimal::add);
}

Holding a lock while calling a method that you do not control, such as a listener or I/O, is the same mistake in a worse form, because its duration is unknown. If a measured block shows 95 percent of its time in a call that needs no shared state, the change is a few lines and the throughput gain is large.

Split one lock into several

A single lock for a whole map makes every thread queue. Lock striping gives each key group its own lock:

java
class StripedCounter {
    private final Object[] locks = new Object[16];
    private final long[] counts = new long[16];

    StripedCounter() {
        for (int i = 0; i < locks.length; i++) locks[i] = new Object();
    }

    void increment(String key) {
        int stripe = Math.floorMod(key.hashCode(), locks.length);
        synchronized (locks[stripe]) {
            counts[stripe]++;
        }
    }
}

With 16 stripes, threads touching different keys rarely collide. In real code, ConcurrentHashMap and LongAdder already do this, so use them before writing striping by hand. A hand-rolled version is justified only when an operation spans a few keys of your own structure.

Pick the tool by the problem

NeedToolWhy
Simple mutual exclusionsynchronizedLeast code, released automatically
Try with a timeout, or interruptible waitingReentrantLocktryLock(timeout), lockInterruptibly()
Many readers, rare writersReadWriteLock or StampedLockReaders do not block each other
A counterLongAdderNo lock at all
A shared mapConcurrentHashMapFine-grained internally
Handing work between threadsBlockingQueueReplaces wait and notify

StampedLock offers optimistic reads that skip locking when no writer is active, at the cost of a harder API and no reentrancy. Use it where a profile shows a read-heavy lock to be the bottleneck.

wait and notify, correctly

Code that uses wait must check its condition in a loop, because a thread can wake with the condition false:

java
synchronized (queue) {
    while (queue.isEmpty()) {
        queue.wait();
    }
    return queue.remove();
}

An if instead of while is a bug that appears rarely, under load. Prefer a BlockingQueue, which holds this logic, tested, in one place. Call notifyAll rather than notify unless exactly one waiter can proceed, since a lost wake-up leaves a thread waiting forever and shows up as a hang with no deadlock to report.

Documenting what a lock protects

Contention problems are hard to fix because nobody remembers what a lock is for. Write one comment on each lock field naming the data it protects and the invariant it keeps, such as "guards balance and history, which must change together". A reader can then judge whether a block is too wide, and a new field is added under the right lock or a new one.

Prefer a private final lock object with a descriptive name over locking on this, so the lock is not exposed to callers. The name and the comment together turn a vague hazard into something that can be reviewed.

Where this does not apply

If you need timeouts, interruptible waits, fairness or multiple conditions, synchronized cannot do them: use [ReentrantLock](/library/java-reentrantlock-use-condition-variables). The Java tutorial on intrinsic locks and the JLS section on synchronization define the semantics.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.