Patterns and antipatterns question 153 of 180 mid
Why is "synchronize everything" a bad strategy?
- It is safe but slow
- Correct: It is both slow and not actually safe: it serialises the application, and holding broad locks across calls to unknown code invites deadlock
- It only affects startup time
- It prevents the JIT from compiling
Locking everything converts a concurrent program into a sequential one with extra overhead, and the scaling curve goes flat or downwards as threads are added.
The correctness half is less obvious and more dangerous. A broad lock is likely to be held while
calling code you do not control: a listener, an overridden method, a callback, a toString on a
user-supplied object. That is an alien call with a lock held, and it is how deadlocks form between
components that were each individually correct.
The discipline: hold the lock for the shortest interval that keeps the invariant, never call unknown
code while holding it, prepare data outside and mutate inside, and document which lock guards which
field (@GuardedBy is worth the annotation).
Quiz yourself on Patterns and antipatterns Suggest a correction