liveBook · Manning

Synchronization

As explained in Troubleshooting Java, Second Edition

Thread synchronization is the coordination of concurrent threads to control their access to shared state and operations.

Thread synchronization coordinates concurrent threads so they do not change shared state simultaneously. Without it, race conditions can cause exceptions, stopped threads, zombie threads, sluggishness, or app failure. section 5.1.1 section 5.2.2

Producers and consumers sharing an ArrayList

Two producer threads add values while two consumer threads read and remove them from a shared ArrayList. The unsynchronized version can throw ArrayIndexOutOfBoundsException and leave threads alive forever. Wrapping both producer and consumer operations in synchronized (Main.list) blocks permits only one thread at a time to perform the compound check-and-change operation. section 5.2.2

Investigate synchronization problems by connecting observable symptoms to runtime evidence:

  • Inspect the Threads tab to identify alive threads and their statuses, then use a thread dump for deeper investigation. section 5.1.1

Synchronization prevents race conditions but introduces locks: waiting threads slow execution, and faulty locking can cause performance problems, freezes, deadlocks, or starvation. Profile first, then use lock profiling when sampling indicates contention. section 7.4

How Troubleshooting Java, Second Edition covers it

How deep it goes
Demonstrates synchronized blocks and profiler observations, then defers deeper lock relationships to thread dumps and lock profiling.
Examples
Uses Java producer and consumer threads that concurrently modify an ArrayList, comparing failing and synchronized executions in VisualVM.
What it assumes
Assumes basic Java threads and collections while teaching race conditions, shared-state hazards, monitors, and profiling observations through small examples.
What you can do after
Diagnose synchronization failures with VisualVM, thread dumps, sampling, and lock profiling, then protect shared access with synchronized blocks.
How it connects
Connects synchronization with race conditions, shared resources, monitors, locks, deadlocks, starvation, thread dumps, and profiling.

Also explained in

Compare how 10 books explain synchronization →

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.