Java Concurrency Interview

Deadlock, livelock and diagnostics question 137 of 180 mid

What four conditions must hold for a deadlock, and which is easiest to break?

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.

deadlock theory

Quiz yourself on Deadlock, livelock and diagnostics Suggest a correction