Video in progress

How do you measure lock contention in prod, and what techniques do you use to reduce it?

JFR's jdk.JavaMonitorEnter/jdk.ThreadPark events or async-profiler's lock mode show which lock is waited on and for how long. To reduce it: shorten the critical section, use lock striping, an immutable snapshot, a lock-free structure, or split the work by thread.

📖 Answer

The signs are usually indirect: throughput doesn't grow as load increases, CPU isn't maxed out, and latency goes up. In a thread dump, many threads are BLOCKED or WAITING (parking) in the same place.

Measuring:

# JFR: monitor waits and parks
jcmd <pid> JFR.start settings=profile duration=2m filename=lock.jfr
jfr print --events jdk.JavaMonitorEnter,jdk.ThreadPark lock.jfr

# async-profiler: a flame graph by lock
asprof -e lock -d 60 -f lock.html <pid>

In JDK Mission Control, the "Lock Instances" view shows which object is waited on the most. Often the answer is somewhere unexpected: a log appender, a synchronized around a SimpleDateFormat, a Hashtable, a global lock in a cache library.

Ways to reduce it, which I usually try in this order:

  1. Shorten the critical section. No IO, logging or JSON serialization inside a lock. Do the computation outside and only do the swap inside.
  2. Get rid of shared state. An immutable object plus a volatile or AtomicReference reference: readers take no lock, and the writer swaps in a new copy.
  3. Striping. N locks instead of one, chosen by the key's hash. ConcurrentHashMap is really this idea.
  4. A ready-made concurrent structure. LongAdder, ConcurrentHashMap.merge, ConcurrentLinkedQueue.
  5. Partitioning. Always send the work for one key to the same thread, and no lock is needed.

After every change, measure again under the same load. Removing a lock sometimes just moves the contention somewhere else, for example to CAS retries or to GC.