liveBook · Manning

Wait/notify approach

As explained in Troubleshooting Java, Second Edition

A wait/notify approach coordinates threads by suspending them with wait and resuming eligible waiting threads with notification.

A wait/notify approach coordinates producer and consumer threads through a shared monitor: a thread waits when work cannot proceed, and another thread calls notifyAll after changing the shared list. section 7.3

Apply the pattern by checking the shared condition while holding the synchronized monitor:

  • Make a consumer wait when the list is empty, then remove a value and notify waiting threads after consumption. section 7.3
  • Make a producer wait when the list reaches capacity, then add a value and notify waiting threads afterward. section 7.3
  • Measure the result instead of assuming fewer locks means faster execution. section 7.3

Bounded producer-consumer list

A consumer synchronizes on the list, removes a value when available, and calls notifyAll; otherwise it calls wait. A producer follows the inverse rule when the list is full. Profiling shows fewer locks but longer waits, making execution slower. section 7.3

Figure 7.14 Locked versus waiting threads. A locked thread is blocked at the entrance of a synchronized block. The monitor won’t allow a thread to enter a synchronized block while another thread actively runs inside the block. A waiting thread is a thread that the monitor has explicitly set to the blocked state. The monitor can make any thread inside the synchronized block it manages wait. The waiting thread can continue its execution only after the monitor explicitly tells it that it can proceed.

Compare a thread locked at a synchronized-block entrance with a thread explicitly placed into the waiting state by its monitor. section 7.3

How Troubleshooting Java, Second Edition covers it

How deep it goes
Shows synchronized wait/notifyAll implementations and profiling results, but stops short of broader optimization guidance.
Examples
Uses a bounded shared list with consumer and producer threads, plus sampling and JProfiler observations.
What you can do after
Diagnose performance changes by comparing lock counts, waiting time, and overall execution speed.
How it connects
Connects monitors, synchronized blocks, producer-consumer coordination, thread locking, and profiling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Troubleshooting Java, Second Edition. The section links point to the parts of the book it draws on.