16.3. Synchronization

Synchronization is a way to arbitrate contention for shared resources. When you synchronize a section of code, a “lock” (or “monitor”) is set when the first thread enters that section of code. Unless the thread explicitly gives up the lock, no other thread can enter that section of code until the first one exits. In fact, synchronization can be even stronger than just locking a single section of code. A synchronized block has an Object as a tag, and once a thread enters a synchronized section of code, no other thread can enter any other section of code that is locked with the same tag.

Synchronizing a Section of Code

The way to protect a section of code that accesses shared resources is to place the code inside a synchronized ...

Get Core Web Programming, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.