Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Clean Code70 XP7 min

Concurrency: Deadlock & Starvation

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

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.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

Hint: The four deadlock conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one to prevent deadlock.

✗ Your version