liveBook · Manning

Locking

As explained in Troubleshooting Java: Read, debug, and optimize JVM applications

A synchronization mechanism that controls concurrent access to a protected resource or code region.

A thread lock makes a thread wait, often while another thread executes a synchronized block. Synchronization protects shared resources from simultaneous changes, but excessive waiting can slow an app or contribute to freezes. section 9.4

To investigate whether locks are hurting performance:

  • Sample execution first. A method whose execution time greatly exceeds its CPU time may be waiting; waiting on itself can point to a lock. section 9.2
  • Use lock profiling to inspect event counts and durations, affected threads, monitors, and which threads block one another. section 9.2
  • Use the results to assess whether synchronization can be improved; aim to reduce waiting and avoid starving threads. section 9.4

Producer and consumer threads

Two threads use the same ArrayList monitor. Profiling shows each blocks the other about 3,700 times, revealing contention around that shared monitor. section 9.2

Figure 9.6 The method doesn’t wait for something, but instead it waits for itself. We observe that its self-execution time is longer than the total CPU time, which usually means that the thread is locked. The thread could have been blocked by another thread.

Compare CPU time with execution time: a large gap can indicate that a thread is blocked. section 9.2

How Troubleshooting Java: Read, debug, and optimize JVM applications covers it

How deep it goes
Explains synchronized-block waits and profiler signals, then traces lock counts, durations, monitors, and thread relationships.
Examples
Uses producer and consumer threads contending on one ArrayList monitor, with roughly 3,700 blocks per thread.
What you can do after
Diagnose lock-related slowdowns by sampling first, then profiling events to identify affected threads, monitors, and blocking relationships.
How it connects
Connects locking with synchronized blocks, monitors, race conditions, deadlocks, thread starvation, and performance profiling.

Also explained in

Compare how 19 books explain locking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Troubleshooting Java: Read, debug, and optimize JVM applications. The section links point to the parts of the book it draws on.