Java Concurrency Interview

Patterns and antipatterns question 153 of 180 mid

Why is "synchronize everything" a bad strategy?

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).

antipatterns performance

Quiz yourself on Patterns and antipatterns Suggest a correction