Part 3 of 6 · 2 min read
Locks
One lock per piece of shared state.
A lock lets one thread at a time run a protected piece of code. In Java, every object has an intrinsic lock, and a synchronized method or block takes it. JCIP states the rule for using it: for each mutable variable that more than one thread may touch, every access must hold the same lock. The variable is then said to be guarded by that lock.
Three points from JCIP deserve care.
- Wrapping only the writes is not enough. Reads need the lock too, or a thread may see a stale or half-updated value. This is why
Locked.get()above is alsosynchronized. - It must be the same lock everywhere. Two different locks for the same variable protect nothing.
- A lock only keeps other threads from taking that same lock. It does not stop them from touching the object by another route. If a new method forgets to lock, the protection quietly fails.
A convention that works well is to put all mutable state of a class behind its own methods, and to lock inside every method that touches it, as SeatMap does. The caller then needs no knowledge of the locking. JCIP adds that each shared mutable variable needs one and only one guarding lock, and that a comment or annotation should name it for maintainers.
Locks have costs. A long critical section makes threads queue and slows the program. Keep the code inside a lock short, and never run slow work, such as a network call, while holding it. EJ Item 79 adds a safety rule: do not call overridable or foreign methods while holding a lock, since you cannot know what they will do. This is the "alien method" warning from the observer module (Level 4, module 2).
Prefer library classes when they fit. ConcurrentHashMap, AtomicInteger, CopyOnWriteArrayList and the blocking queues of module 4 are already correct and well tested. EJ Item 81 says to prefer such utilities to hand-written locking and waiting.
Lock
A lock is a tool that lets only one thread at a time enter a piece of code, while other threads wait for their turn.
Example: the synchronized keyword on SeatMap.reserve.
Check yourself: 1. Why must reads also take the lock? 2. What must be true of the lock used for one variable? 3. What should never be done while a lock is held?