Skip to main content
Clean Code 70 XP · 7 min

Concurrency: Deadlock & Starvation

Recognize and eliminate the four conditions that produce deadlock in concurrent systems.

Showing
Ad (728×90)

The Four Deadlock Conditions

Coffman's conditions: (1) Mutual exclusion — resources cannot be shared. (2) Hold and wait — a thread holds one resource while waiting for another. (3) No preemption — resources cannot be forcibly taken. (4) Circular wait — a cycle of threads each waiting for the next. All four must be present. Break any one to prevent deadlock.

Breaking the Circular Wait

The most practical solution: acquire all locks in a consistent global order. If every thread acquires lock A before lock B, circular wait is impossible. Another strategy: use timeouts — if a lock cannot be acquired within a deadline, release all held locks and retry.

Code Challenge

Identify the circular wait, then apply canonical lock ordering to fix it.

Key takeaway

Most deadlocks share one fix: always acquire multiple locks in the same canonical order throughout the entire codebase.

Done with this lesson?

Mark it complete to earn XP and track your progress.