Skip to content

Path 3 · lesson 3 of 6

Intermediate30 minJava 21 (OpenJDK 21.0.13, HotSpot) · Spring Boot 3.5

synchronized, volatile and happens-before

What an intrinsic lock guards and what it does not, what volatile adds and what it cannot, the five happens-before rules you actually use, and double-checked locking done wrong and right.

What you will learn

  • State which monitor a synchronized instance method, static method and block each lock, and find it in bytecode and in a thread dump
  • Decide whether a field is actually guarded: same lock on every access, reads included
  • Say exactly what volatile guarantees and name the two conditions under which it is sufficient on its own
  • Use the happens-before rules for monitors, volatile, start, join and final fields to argue that a piece of code is correct
  • Explain why double-checked locking without volatile is broken and write the correct form
  • Measure the cost of a lock with a thread dump and JFR, and know when synchronized hurts virtual threads on JDK 21

Before you start

The concept

The previous lesson separated two problems: compound actions that are not atomic, and writes that are not visible. Java's two oldest tools line up with them. synchronized solves both for everything done while holding a lock. volatile solves visibility for one field and nothing else. Happens-before is the rule book that says why each of them works, and it is what you reason with when the code does not look like a textbook example.

synchronized: one owner at a time

Every Java object has a monitor, also called its intrinsic lock. Only one thread at a time can hold it; any other thread that tries is blocked until it is released. synchronized is the only way to take it:

FormMonitor that is lockedReleased
synchronized void m() (instance method)The monitor of thisWhen the method returns or throws
static synchronized void m()The monitor of the Class object of the method's classWhen the method returns or throws
synchronized (expr) { ... }The monitor of the object expr evaluates toWhen the block is left, normally or by exception
Java Language Specification 8.4.3.6 and 17.1.

Three properties matter in practice. The lock is reentrant: a thread that holds a monitor can take it again, and each unlock undoes one lock. It is always released, including when an exception leaves the block. And it brings visibility with it: an unlock of a monitor happens-before every later lock of that same monitor, so whatever one thread wrote while holding the lock is seen by the next thread that takes it.

volatile: every read sees the last write

A volatile field has one guarantee: a write to it happens-before every later read of it. Readers never use a cached value, and they also see everything the writer did before the write. The java.util.concurrent documentation puts the limit in one sentence: volatile reads and writes have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking. No thread ever waits for a volatile, and no two operations on it are ever joined into one.

synchronized

  • Mutual exclusion and visibility.
  • Covers any number of fields and steps, as long as every access takes the same lock.
  • Threads that lose wait in state BLOCKED. The wait is visible in thread dumps and JFR.
  • Right for invariants across fields and for compound actions that atomics cannot express.

volatile

  • Visibility and ordering only.
  • Covers one field. v++ and check-then-act on it are still races.
  • Nobody ever waits. Nothing to see in a thread dump.
  • Right for a flag, or a reference to an immutable object that is replaced as a whole.

Why it exists

Most concurrency defects in service code are not exotic. They are a synchronized on the wrong object, a getter that skips the lock, a volatile asked to do a lock's job, or a lazy initialisation copied from an old blog post. Each one compiles, passes review and passes tests.

  • Wrong lock. Two threads synchronise on different objects and exclude nobody. The run below loses 19.1% of its updates while every increment sits inside a synchronized block.
  • Half-guarded state. Writes take the lock, a read does not. The reader can see two fields that do not belong together, or a stale value.
  • Too much inside the lock. A remote call inside synchronized turns one slow dependency into a queue of BLOCKED request threads. See lock contention.
  • Unsafe publication. An object is handed to other threads through a plain field, and a thread sees the reference before the values of its fields.
  • Pinned virtual threads. On JDK 21 a virtual thread that blocks inside synchronized cannot unmount from its carrier thread.

How it works inside

What the compiler emits

A synchronized block becomes two bytecode instructions around the body. This is javap on a counter with one block-synchronised and one method-synchronised increment:

Program outputjavap -c -p 'SyncHappensBefore$Counter' (two of its methods)

Real JVM output
  void blockIncrement();
    Code:
       0: aload_0
       1: getfield      #7                  // Field lock:Ljava/lang/Object;
       4: dup
       5: astore_1
       6: monitorenter
       7: aload_0
       8: dup
       9: getfield      #13                 // Field hits:I
      12: iconst_1
      13: iadd
      14: putfield      #13                 // Field hits:I
      17: aload_1
      18: monitorexit
      19: goto          27
      22: astore_2
      23: aload_1
      24: monitorexit
      25: aload_2
      26: athrow
      27: return
    Exception table:
       from    to  target type
           7    19    22   any
          22    25    22   any

  synchronized void methodIncrement();
    Code:
       0: aload_0
       1: dup
       2: getfield      #13                 // Field hits:I
       5: iconst_1
       6: iadd
       7: putfield      #13                 // Field hits:I
      10: return
In blockIncrement, offset 6 is monitorenter on the object loaded from the lock field, and there are two monitorexit instructions: offset 18 on the normal path and offset 24 in a handler that the exception table installs for any throwable, which releases the lock and rethrows. That table is why a synchronized block cannot leak its lock. methodIncrement has no monitor instructions at all: the method carries the ACC_SYNCHRONIZED flag (visible with javap -v) and the JVM enters and exits the monitor as part of invoking and returning.

Between monitorenter and monitorexit the increment is the same getfield, iadd, putfield as before. The lock does not make those three instructions one instruction. It makes sure no other thread that takes the same lock runs them in between.

What is guarded, and what is not

extras/SyncHappensBefore.java has 8 threads add to one shared total. In the first run each worker object synchronises on this, and there are 8 worker objects. In the second, all of them synchronise on one shared lock object.

Program outputjava -XX:ActiveProcessorCount=2 -Xmx64m SyncHappensBefore.java

Real JVM output
8 threads x 200,000 increments of one shared total, expected 1,600,000

synchronized (this), one lock per thread   result 1,293,938   lost   306,062 (19.1%)
synchronized (sharedLock), one lock        result 1,600,000   lost         0 ( 0.0%)
Every increment in the first run is inside a synchronized block and 306,062 of 1,600,000 are lost. Eight different monitors exclude nobody. With one monitor the result is exact.

This is the wrong-lock defect in its purest form, and it has common disguises:

  • synchronized (this) in an object that is not shared. A per-request or prototype-scoped object guarding a static field or another bean's state.
  • An instance method guarding static state. synchronized void add() locks this; a static counter needs the class's monitor or a static lock object.
  • A lock field that is reassigned. synchronized (cache) { cache = new HashMap<>(); }: the next thread locks the new object while the first is still inside. Lock objects should be private final.
  • A lock that other code can reach. synchronized (this) on a public bean lets any caller hold your lock for as long as it likes. A private final Object lock cannot be taken from outside.
  • Reads without the lock. A getter that returns a guarded field with no lock has no happens-before edge with the writers, and can observe a multi-field update halfway.

Reentrancy removes one worry: a synchronized method may call another synchronized method on the same object without blocking itself. The same program shows it:

Program outputSyncHappensBefore.java, reentrancy part

Real JVM output
reentrancy: addTwice() is synchronized and calls methodIncrement(), also synchronized on this
  returned 2 without blocking; Thread.holdsLock(c) afterwards: false
addTwice() holds the monitor of the counter and calls methodIncrement() twice, which takes the same monitor again each time. It returns 2 and, afterwards, Thread.holdsLock(c) is false: every entry was matched by an exit.

The happens-before rules you actually use

A write is guaranteed to be visible to a read in another thread only if the write happens-before the read. Five rules create such edges between threads, plus program order inside each thread and transitivity to chain them.

RuleStatementWhat it lets you do
MonitorAn unlock of a monitor happens-before every later lock of that monitorUse plain fields for state that is only touched under one lock
VolatileA write to a volatile field happens-before every later read of that fieldPublish a flag or a reference without a lock
StartA call to start() happens-before any action in the started threadConfigure an object, then start the thread that uses it, with no further guard
JoinAll actions in a thread happen-before another thread returns from join() on itRead a worker's results from plain fields after joining it
Final fieldsA thread that can only see a reference to an object after its constructor has finished is guaranteed to see the correct values of its final fieldsShare immutable objects freely, however the reference travelled
Program orderWithin a thread, each action happens-before those that come laterChain the rules above: what you did before the unlock or the volatile write travels with it
Java Language Specification 17.4.5 and 17.5. The java.util.concurrent classes add their own edges, such as submitting a task to an executor.

Transitivity is what makes the rules practical. If thread A fills in three plain fields of an object and then writes the reference to a volatile field, and thread B reads the volatile field and then the three fields, B is guaranteed to see all three: A's field writes come before A's volatile write in program order, the volatile write happens-before B's read, and B's field reads come after that in program order. The edge carries everything that came before it.

volatile in detail

The lost updates lab runs the same 1,600,000 increments on a volatile field and under a lock:

Program outputlabs/jvm/lost-updates: java LostUpdate.java (two of five rows)

Real JVM output
8 threads x 200,000 increments, expected 1,600,000

volatile int                     result   951,024   lost   648,976 (40.6%)     15 ms
synchronized block               result 1,600,000   lost         0 ( 0.0%)     34 ms
The volatile counter lost 648,976 increments. Every one of its reads returned the latest value, and that was not the problem. The synchronized counter is exact, and in this run took 34 ms against 15 ms: that difference is the price of making 8 threads take turns.

volatile is sufficient on its own when both of these hold:

  1. Writes do not depend on the current value, or only one thread ever writes. stop = true and current = newSnapshot qualify. count++ and if (x == null) x = ... do not.
  2. The field is not tied to other state by an invariant. Two volatile fields lower and upper cannot keep lower <= upper: a reader can see one from before an update and the other from after.

Its most useful form in services is the immutable snapshot: build a complete new object, then replace a volatile reference to it in one write. Readers take the reference once and work with a consistent view. Two more facts from the specification: a volatile long or double is always read and written atomically, unlike a plain one; and a field cannot be both final and volatile.

Final fields and safe publication

Creating an object correctly is not enough: the reference has to reach other threads through an edge too. If it travels through a data race, a reader can see the reference and still see default values in the object's non-final fields. Final fields have a special rule: once the constructor has finished, any thread that obtains the reference sees the final fields as the constructor set them, provided the constructor did not let this escape, for example by registering itself as a listener or starting a thread.

Way to publish an objectWhy it is safe
Store it in a volatile field or an AtomicReferenceVolatile rule
Store it in a field that is only read and written under one lockMonitor rule
Initialise it in a static initialiser (static final, or the holder class idiom)Class initialisation takes a per-class lock, and other threads wait until it has completed
Put it into a concurrent collection or hand it to an executorThe java.util.concurrent rules
Make every field final and do not leak this from the constructorFinal field rule: safe however the reference is passed
Create it before start() of the thread that uses itStart rule

Spring does this for you in the common case. Non-lazy singleton beans are normally created and wired during context start-up, before the application serves requests, and constructor injection into final fields puts collaborators under the final field rule. The danger is state you add after start-up: lazily created objects and refreshed caches.

Double-checked locking

Double-checked locking tries to initialise something lazily while paying for a lock only on the first call: check the field without a lock, and only if it is null take the lock and check again. The first check is a read with no lock, so it is only correct if that read has a happens-before edge with the write. With a plain field it has none: the write happens under the lock, and the monitor rule only helps threads that take the lock. With a volatile field the volatile rule supplies the edge. The broken and the correct form are in the section on the mistake and its repair below.

Architecture

Drawing diagram…

A flowchart of happens-before edges. Thread A builds an object, then writes its reference to a volatile field. The volatile rule links that write to thread B's read of the field, and program order links B's read to its later reads of the object's fields. By transitivity B sees A's field writes. A second, separate pair of boxes shows the same code with a plain field: there is no edge between the threads, so thread B may see null or a reference without the field values.

flowchart LR
    A1["Thread A: build the object and fill its fields"] -->|"program order"| A2["Thread A: write the reference to a volatile field"]
    A2 -->|"volatile rule"| B1["Thread B: read the volatile field"]
    B1 -->|"program order"| B2["Thread B: read the object's fields"]
    A1 -.->|"therefore visible, by transitivity"| B2
    P1["Same code with a plain field"] -.->|"no edge between the threads"| P2["Thread B may see null, or the reference without the field values"]
How a volatile write carries earlier plain writes to the reader, and what is missing without it.
  • Only one edge in the chain crosses between threads: the volatile write to the volatile read. Everything else is program order inside one thread.
  • The dotted arrow is the conclusion, not a rule of its own. It is why a snapshot object built before the volatile write does not need volatile fields itself.
  • The chain only covers what A did before the volatile write. If A modifies the object afterwards, those writes have no edge to B. Publish last, and do not mutate after publishing.
  • Replace the volatile field by a lock taken by both threads and the picture is the same, with the unlock and the later lock as the crossing edge.

Step by step

Drawing diagram…

A sequence diagram with two request threads and the monitor of a lock object. Thread A enters the monitor. Thread B tries to enter and is blocked. Thread A changes two fields, available and reserved, then exits the monitor. Thread B then acquires the monitor and reads both fields with the values thread A wrote, and exits.

sequenceDiagram
    participant A as Request thread A
    participant M as Monitor of the ledger lock
    participant B as Request thread B
    A->>M: monitorenter, acquired
    B->>M: monitorenter
    Note over B,M: B is BLOCKED, waiting to lock
    A->>A: available 500 to 497, reserved 0 to 3
    A->>M: monitorexit
    Note over A,B: unlock happens-before the next lock
    M-->>B: acquired
    B->>B: reads available 497 and reserved 3
    B->>M: monitorexit
Two request threads and one monitor: exclusion while A updates two fields, visibility when B gets the lock.
  1. While A is between monitorenter and monitorexit, B cannot observe the state in which available is already reduced and reserved not yet raised. That is mutual exclusion.
  2. When B acquires the monitor, the monitor rule guarantees it sees both of A's writes although neither field is volatile. That is visibility.
  3. B's time in BLOCKED is the cost. It is exactly as long as A's critical section, so the rule for critical sections is: short, and no I/O.
  4. A thread that reads the two fields without taking the lock is not in this diagram at all. It gets neither guarantee.

In a real system

A correct lock still has a price, and the price is paid in waiting. Three artefacts show it.

The thread dump shows who holds a monitor and who wants it. The frame under which a - locked line is printed is the method that took the lock:

Thread dumplabs/jvm/lock-contention: jcmd <pid> Thread.print (one of seven waiters, and the owner)

Real JVM output
"view-counter-1" #24 [4627] prio=5 os_prio=0 cpu=798.40ms elapsed=3.65s tid=0x00007e8754632810 nid=4627 waiting for monitor entry  [0x00007e872dafc000]
   java.lang.Thread.State: BLOCKED (on object monitor)
	at LockContention.recordGlobal(LockContention.java:23)
	- waiting to lock <0x00000000f3500540> (a java.util.HashMap)
...

"view-counter-5" #28 [4631] prio=5 os_prio=0 cpu=890.45ms elapsed=3.65s tid=0x00007e87546375f0 nid=4631 runnable  [0x00007e872d6fb000]
   java.lang.Thread.State: RUNNABLE
	at LockContention.spin(LockContention.java:37)
	at LockContention.recordGlobal(LockContention.java:25)
	- locked <0x00000000f3500540> (a java.util.HashMap)
...
view-counter-1 is BLOCKED (on object monitor) and waiting to lock <0x00000000f3500540> (a java.util.HashMap). view-counter-5 shows - locked <0x00000000f3500540> under recordGlobal, and above it the frame spin: that is the work being done while the lock is held. The monitor is a HashMap used as a lock, shared by all 8 threads.

JFR shows how long threads waited. The event jdk.JavaMonitorEnter records each wait for a monitor that lasted longer than a threshold (20 ms in the JDK's default.jfc, 10 ms in profile.jfc), and jfr view contention-by-site adds them up per code location:

JFRlabs/jvm/lock-contention: jfr view contention-by-site contention.jfr

Real JVM output
                               Contention by Site

StackTrace                                                Count    Avg.    Max.
--------------------------------------------------------- ----- ------- -------
LockContention.recordGlobal(String)                         894 22.7 ms 58.7 ms
One site, 894 recorded waits in a 5 second run, 22.7 ms on average and 58.7 ms at worst, for a critical section short enough to run 563,433 times a second. Waits shorter than the threshold are not in the count, so the real number of waits is higher.

Throughput shows what the waiting costs. Same machine, same 8 threads, first with one global lock and then with a ConcurrentHashMap and LongAdder:

Program outputlabs/jvm/lock-contention: java LockContention.java global, then striped

Real JVM output
global: 2,817,166 updates in 5 s = 563,433 updates/s
striped: 5,660,929 updates in 5 s = 1,132,185 updates/s
563,433 updates per second through one monitor, 1,132,185 without it: twice the throughput on 2 CPUs. The lock was correct. It was also the bottleneck.

Virtual threads on JDK 21 add a second cost. A virtual thread that blocks while inside a synchronized block or method is pinned: it cannot unmount, so it keeps its carrier platform thread blocked as well. The virtual threads lab lets 40 virtual threads sleep 100 ms inside synchronized on 2 carriers, with -Djdk.tracePinnedThreads=short:

Program outputlabs/jvm/virtual-threads: java -Djdk.tracePinnedThreads=short VirtualThreads.java pinned

Real JVM output
VirtualThread[#19]/runnable@ForkJoinPool-1-worker-1 reason:MONITOR
    VirtualThreads.lambda$pinned$1(VirtualThreads.java:61) <== monitors:1
pinned: 40 virtual threads sleeping 100 ms inside synchronized took 2,011 ms on 2 carrier threads (unpinned it would take about 100 ms)
The first two lines are the JDK's pinning trace: reason:MONITOR and the frame that holds the monitor. The last line is the cost: 2,011 ms for work that would take about 100 ms unpinned. Oracle's guidance for JDK 21 is to replace synchronized with ReentrantLock only where it guards frequent or long blocking operations, not everywhere. See virtual threads and locks.
  • Keep critical sections to memory operations. Do the remote call or the query outside the lock, then take the lock to store the result.
  • Prefer not sharing over locking: an immutable snapshot behind a volatile reference has no waiters at all.
  • When the dump shows many threads BLOCKED on one address, the question is always what the owner is doing while holding it. If the owner changes from dump to dump, the lock is hot. If it is always the same thread, that thread is stuck.

Java and Spring Boot

Two beans from a Spring Boot 3.x service, one for each tool. Both were compiled with javac 21 against stand-in stubs for @Service and @Scheduled, not against Spring itself. @Scheduled needs @EnableScheduling on a configuration class to take effect.

src/main/java/com/example/pricing/rates/ExchangeRateCache.javaJava
package com.example.pricing.rates;import java.time.Instant;import java.util.Map;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;/** Read on every request, replaced every 30 s by one scheduler thread. */@Servicepublic class ExchangeRateCache {    /** Immutable: final fields, and Map.copyOf returns an unmodifiable copy. */    public record Rates(Map<String, Double> byPair, Instant loadedAt) {        public Rates {            byPair = Map.copyOf(byPair);        }    }    private final RateProvider provider;    private volatile Rates current = new Rates(Map.of(), Instant.EPOCH);    public ExchangeRateCache(RateProvider provider) {        this.provider = provider;    }    @Scheduled(fixedDelay = 30_000)    void refresh() {        Rates next = new Rates(provider.fetchAll(), Instant.now());   // build completely first        current = next;                                              // then publish with one volatile write    }    public double rate(String pair) {        Rates rates = current;                    // one volatile read: this request uses one consistent table        Double rate = rates.byPair().get(pair);        if (rate == null) {            throw new IllegalArgumentException("no rate for " + pair + " in table loaded at " + rates.loadedAt());        }        return rate;    }}

Why it is written this way

  • Rates is immutable: a record's fields are final and the compact constructor replaces the map by an unmodifiable copy. After construction nothing about it can change.
  • current is volatile and is only ever overwritten as a whole. The write does not depend on the old value, and there is one writer: both conditions for volatile alone are met.
  • refresh() builds the new table completely and publishes it last. A reader sees the old table or the new one, never a half-filled one.
  • rate() reads current once into a local. Two reads could straddle a refresh and return a rate from one table and a timestamp from another.
  • No reader ever waits, however long provider.fetchAll() takes, because the slow call is not inside any lock.

Wrong, then right

Fraud rules that take about two seconds to load, initialised lazily on the first payment with double-checked locking. Both versions were compiled with javac 21 against a stand-in stub for @Component. The failure of the first version was not reproduced on a real JVM for this lesson; it is argued from the memory model.

Incorrect implementation

src/main/java/com/example/payments/fraud/FraudRulesProvider.javaJava
package com.example.payments.fraud;import org.springframework.stereotype.Component;@Componentpublic class FraudRulesProvider {    private final RulesRepository repository;    private FraudRules rules;                     // not volatile    public FraudRulesProvider(RulesRepository repository) {        this.repository = repository;    }    /** Lazy: the first payment loads the rules (about 2 s), later payments reuse them. */    public FraudRules rules() {        if (rules == null) {                      // 1st check: a read with no lock            synchronized (this) {                if (rules == null) {              // 2nd check: under the lock                    rules = repository.loadAll(); // write under the lock                }            }        }        return rules;                             // another read with no lock    }}

Why it is written this way

  • The write is under the lock. The first check and the final return rules are reads with no lock, and the field is not volatile.
  • FraudRules is a mutable class whose fields are filled in by the repository after construction.

Why it fails

  • The first if (rules == null) reads a plain field outside the lock. The monitor rule creates an edge only between an unlock and a later lock, and this read takes no lock, so no happens-before edge links it to the write. It is a data race.
  • Without an edge, a thread that sees a non-null reference has no guarantee about what it sees through it. The fields of FraudRules are not final, so the reader may observe them with default values: a null list of blocked countries, a maximum amount of 0. The reference can become visible before the writes that filled the object.
  • The symptom would be one request, shortly after start-up, that fails with a NullPointerException deep inside rule evaluation, or that evaluates a payment against empty rules and lets it through. It cannot be repeated on demand, and by the time anyone looks the object is complete.
  • The method reads the field twice outside the lock, at the check and at the return. They are two independent racy reads, and the specification does not promise that the second agrees with the first.
  • Whether the failure ever occurs depends on the JIT compiler and the CPU's memory ordering, and on common x86-64 hardware it may never be observed. That is an argument about one platform and one JDK build. The code is incorrect by the specification, and the next platform or compiler is free to expose it.

Corrected implementation

src/main/java/com/example/payments/fraud/FraudRulesProvider.javaJava
package com.example.payments.fraud;import org.springframework.stereotype.Component;@Componentpublic class FraudRulesProvider {    private final RulesRepository repository;    private final Object initLock = new Object();    private volatile FraudRules rules;            // volatile: the write happens-before every later read    public FraudRulesProvider(RulesRepository repository) {        this.repository = repository;    }    public FraudRules rules() {        FraudRules local = rules;                 // one volatile read on the fast path        if (local == null) {            synchronized (initLock) {                local = rules;                    // re-read under the lock                if (local == null) {                    local = repository.loadAll(); // fully built before it is published                    rules = local;                // volatile write publishes it                }            }        }        return local;    }}

Why it is written this way

  • volatile supplies the missing edge: the write of rules happens-before every later read, and by program order and transitivity so do the writes that filled the object before it was assigned.
  • The field is read into local once on the fast path. The method returns that same value, so there is exactly one volatile read per call after initialisation.
  • The object is fully loaded into local first and assigned to the field last. Publishing is the final step.
  • A private lock object replaces synchronized (this), so nothing else that synchronises on the bean can delay initialisation.

Trade-offs

  • Every call now performs a volatile read. It is cheap, but it is not free, and it is paid for ever to save a lock that was only needed once.
  • The first call holds initLock for the full two seconds of loading. Every payment that arrives in that time queues behind it in state BLOCKED.
  • If loadAll() throws, nothing is stored and the next caller tries again, so a broken repository is hit by every request, one at a time, each holding the lock.
  • The simpler design is usually better: let Spring build the rules at start-up as an ordinary singleton bean with final fields. The cost moves to start-up time, where a failure stops the deploy before traffic arrives, and the code needs neither volatile nor a lock. When laziness is really needed for a static singleton, a static final field in a nested holder class gets the same effect from class initialisation.

Configuration

There is nothing to tune for synchronized or volatile themselves. These are the switches that make their cost visible on JDK 21.

-Djdk.tracePinnedThreadsDefault none (not set, no trace)
What it does
With full, prints a complete stack trace when a virtual thread blocks while pinned, highlighting native frames and frames holding monitors. With short, prints only the problematic frames.
When to change it
Set it in a test environment when moving a service to virtual threads, to find synchronized blocks that contain blocking calls. Replace only those that are frequent or long.
jdk.JavaMonitorEnter threshold (JFR)Default 20 ms in default.jfc, 10 ms in profile.jfc (JDK 21.0.13)
What it does
A wait for a monitor is recorded as an event only if it lasted at least this long.
When to change it
Record with settings=profile when investigating contention. Remember that shorter waits are invisible: many 2 ms waits add up and never appear.
jcmd <pid> Thread.print -lDefault false
What it does
Also prints java.util.concurrent locks owned by each thread. Monitors taken with synchronized are always printed.
When to change it
Not needed for synchronized. Needed as soon as the code uses ReentrantLock, whose owners are otherwise not shown.

Hands-on exercise

Find out what volatile changes, and what only a lock changes

Use the simulation to check, step by step, that volatile does not stop two threads from reading the same value, and that under a lock the losing interleaving cannot be constructed at all.

Steps · 0 of 6 done

volatile against synchronized, one step at a time

Simulation · not a real JVM

Step two threads through read, add and write on one counter. Start with a volatile counter, then put the same steps under a lock. This is a simulation, not a running JVM.

Take it further in the simulation: Lost updates: counter++ is three steps

What can go wrong

Synchronising on an object that is not shared
Symptom
Updates are lost although every one of them is inside a synchronized block.
Cause
The threads lock different monitors: this of different instances, an instance lock for static state, or a lock field that is reassigned.
Fix
One private final lock object with the same lifetime and scope as the state it guards. For static state, a private static final lock.
Guarding writes and not reads
Symptom
A status endpoint occasionally reports totals that do not add up, or a value that is seconds old.
Cause
The getter does not take the lock, so it has no happens-before edge with the writers and can run in the middle of a multi-field update.
Fix
Take the same lock for reads, or publish an immutable snapshot through a volatile field and read that.
volatile on a reference to a mutable object
Symptom
A volatile Map or volatile List field, and still stale or corrupted contents.
Cause
volatile covers the reference, that is, the assignment to the field. Calls such as map.put(...) do not write the field and get no guarantee from it.
Fix
Either never mutate after publishing (replace the whole object), or use a concurrent collection in a final field.
Blocking calls inside synchronized
Symptom
Under load most request threads are BLOCKED on one monitor and latency follows the slowest downstream call.
Cause
The owner holds the lock across a database query or an HTTP call, so every other caller waits for that call too. On JDK 21 virtual threads the same pattern pins carrier threads.
Fix
Do the slow work outside the lock and take the lock only to read or store its result. Where a lock must span blocking work on virtual threads, use ReentrantLock.
Double-checked locking without volatile
Symptom
A rare NullPointerException or a half-initialised object right after start-up, never reproducible.
Cause
The unlocked first check reads a plain field, so the reference can be seen without the writes that initialised the object.
Fix
Declare the field volatile and read it once into a local, or avoid the idiom: eager initialisation as a bean, or a static holder class.

How to troubleshoot

Many request threads are BLOCKED

Check

jcmd <pid> Thread.print | grep 'waiting to lock' | sort | uniq -c | sort -rn
How to read it
Counts waiters per monitor address and class. Take the top address and search the dump for - locked <address>: that thread is the owner, and the frames above the - locked line are what it does while holding the lock.
You need to know how much time a lock costs

Check

jcmd <pid> JFR.start name=locks settings=profile duration=60s filename=/tmp/locks.jfr   then   jfr view contention-by-site /tmp/locks.jfr
How to read it
Lists each code location where threads waited for a monitor, with the number of recorded waits and their average and maximum length. jfr print --events jdk.JavaMonitorEnter /tmp/locks.jfr shows the individual events, including the previous owner of the monitor.
You are not sure a method really takes a lock, or which one

Check

javap -c -p -v -cp target/classes com.example.inventory.StockLedger | grep -E 'monitorenter|monitorexit|ACC_SYNCHRONIZED'
How to read it
monitorenter and monitorexit come from synchronized blocks; the instruction before monitorenter in the full listing shows which object is loaded as the lock. ACC_SYNCHRONIZED marks synchronized methods, which lock this or, for static methods, the class.
A field is supposed to be guarded and updates are still lost

Check

assert Thread.holdsLock(lock);   at the top of every method that touches the field, run with java -ea
How to read it
Thread.holdsLock(obj) is true only if the current thread owns that object's monitor. An AssertionError in tests names the code path that reaches the field without the lock.
A service on virtual threads is no faster, or stalls

Check

java -Djdk.tracePinnedThreads=short -jar app.jar
How to read it
Each trace names a frame that blocked while holding a monitor, with reason:MONITOR. Frequent traces from the same frame mean that synchronized block is holding carrier threads.

Key takeaways

  • synchronized locks one specific object's monitor. Exclusion and visibility apply only among threads that lock that same object.
  • A field is guarded only if every read and every write of it happens under the same lock. The language does not check this for you.
  • volatile makes the latest write, and everything the writer did before it, visible to readers. It never makes two steps atomic.
  • volatile alone is right when writes do not depend on the old value and the field is not tied to other state: flags and whole-object snapshots.
  • Five rules carry writes between threads: monitor unlock to lock, volatile write to read, start, join, and final fields of a properly constructed object.
  • Double-checked locking needs a volatile field. Better still, initialise eagerly and keep the fields final.
  • A correct lock can still be the bottleneck: one global monitor halved throughput in the lab, and on JDK 21 it pins virtual threads that block inside it.

Practical check

Small scenarios, one decision each. Pick what you would do, then read why.

Scenario 1 of 4

A @Component with prototype scope is created for every import job. It contains private static int imported; and a method synchronized void record() { imported++; }. Six jobs run in parallel, each on its own instance. After 600,000 records the counter shows 571,204.

Why are updates lost although the method is synchronized?

Scenario 2 of 4

A settings bean holds private volatile Map<String, String> flags = new HashMap<>();. An admin endpoint calls flags.put(name, value) and request threads call flags.get(name). Occasionally a request does not see a flag that was set minutes earlier, and once a ConcurrentModificationException appeared in a debug endpoint that iterates the map.

What is wrong, and what is the smallest correct change?

Scenario 3 of 4

A lazily created HTTP client is initialised with if (client == null) { synchronized (this) { if (client == null) client = build(); } } return client; and client is a plain field. A colleague argues it has run for two years on x86-64 servers without one failure, so it is fine. The team is about to move to ARM instances.

What is the right assessment?

Scenario 4 of 4

During a traffic peak, three thread dumps five seconds apart each show about 180 of 200 request threads BLOCKED (on object monitor), all waiting to lock <0x00000007123a9f10> (a com.shop.PriceCache). In each dump a different thread has - locked <0x00000007123a9f10>, and above that line its stack is in an HTTP client waiting for a response.

What should change?

References

References: Java Language Specification, Java SE 21, chapter 17: Threads and Locks (17.1 synchronization, 17.4.5 happens-before, 17.5 final field semantics, 17.7 long and double) ↗ · Java Language Specification, Java SE 21, chapter 8: Classes (8.3.1.4 volatile fields, 8.4.3.6 synchronized methods) ↗ · Java Language Specification, Java SE 21, chapter 12: Execution (12.4 class initialization and its lock) ↗ · Java Virtual Machine Specification, Java SE 21, 2.11.10: Synchronization (ACC_SYNCHRONIZED, monitorenter, monitorexit) ↗ · Java SE 21 API: java.util.concurrent, Memory Consistency Properties ↗ · Java SE 21 Core Libraries: Virtual Threads (pinning inside synchronized, jdk.tracePinnedThreads) ↗ · Java SE 21 API: Thread (holdsLock) ↗ · JDK 21 tool reference: jcmd (Thread.print) ↗ · Spring Framework reference: Bean scopes (singleton and prototype) ↗ · Report a problem