00:00

Problem Statement

Input/Output Examples

Visual Explanation

A deadlock needs four conditions at once: mutual exclusion, hold and wait, no pre-emption and a circular wait. Each fix removes one of them.

Approaches

Both approaches make the transfers deadlock-free. The first removes the circular wait; the second removes hold and wait.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both tabs print the same output; the program exits explicitly so a regression to a deadlock cannot hang it.

Complexity Analysis

Each transfer does a constant amount of work. Ordered locking never retries; tryLock() may retry a few times under contention.

Interview Tips and Recommended Approach

  • Name the four Coffman conditions and say which one your fix breaks.
  • Find deadlocks with a thread dump. jstack reports "Found one Java-level deadlock".
  • Avoid calling unknown code while holding a lock; it may take other locks in any order.
  • Prefer fewer, coarser locks when the contention is low; one lock cannot deadlock with itself.

Recommended Approach: Global Lock Order

Why: it removes the cause of the deadlock instead of recovering from it, adds no retries and is easy to explain.