Deadlock, livelock and diagnostics question 137 of 180 mid
What four conditions must hold for a deadlock, and which is easiest to break?
- Two threads and two locks, nothing more
- Correct: Mutual exclusion, hold and wait, no preemption, and circular wait; circular wait is the one you break in practice by imposing a lock ordering
- Only circular wait
- Deadlock requires at least three threads
All four Coffman conditions must hold at once, so removing any one prevents deadlock. In Java you cannot remove mutual exclusion (that is the point of a lock) and you cannot preempt a monitor.
That leaves two. Break hold-and-wait with tryLock and a timeout: acquire what you can, release
everything and retry if you cannot. Break circular wait with a global lock ordering: if every thread
takes locks in the same order, no cycle can form. For dynamic objects the order can be derived, for
instance from System.identityHashCode, with a tie-breaker lock for the rare collision.
The cheapest defence of all is not holding two locks, which is usually achievable by narrowing the critical sections.
Quiz yourself on Deadlock, livelock and diagnostics Suggest a correction