DeadlocksWhat is Deadlock?Medium⏱️ ~2 min

Real-World Deadlock Examples

Learning From Bugs
Real deadlocks are often subtle and surprising. They hide in innocent-looking code and strike under specific conditions.

Pattern 1: Lock Ordering Violation

Function A acquires lock X then Y. Function B acquires lock Y then X. Both are correct individually. Called concurrently? Deadlock. This is the most common cause.

Pattern 2: Callback Holding Lock

Thread holds lock, calls a callback or listener. Callback tries to acquire the same lock (reentrant) or a different lock held by another thread waiting for this one. Hidden dependency causes deadlock.

Pattern 3: Thread Pool Exhaustion

Task A runs on thread pool, submits Task B to same pool, waits for B. If pool is full, B cannot start. A waits for B, B waits for a free thread, all threads wait for A. Circular dependency on threads.

Thread Pool Deadlock
Task Awaits for BThread PoolFULL (all busy)Task Bqueued, cannot run

Pattern 4: Database Deadlock

Transaction 1 updates rows in order A, B. Transaction 2 updates rows in order B, A. Classic lock ordering problem at the database level. Most databases detect this and abort one transaction.

Common Theme: Most deadlocks come from inconsistent ordering - of locks, of resource acquisition, of task dependencies. Establish and enforce a global order to prevent them.
💡 Key Takeaways
Lock ordering violation: A locks X→Y, B locks Y→X. Most common deadlock pattern.
Callback deadlock: holding lock while calling external code that might need the same lock.
Thread pool exhaustion: task waits for subtask, but no threads available. Circular wait on threads.
Database row locks: transactions update rows in different orders. Detected and one is aborted.
Common fix: establish global ordering for locks and resources. Always acquire in same order.
📌 Examples
1Transfer money: transfer(A,B) locks A then B. transfer(B,A) locks B then A. Called together: deadlock.
2Event listener: notify listeners while holding lock. Listener tries to modify the object. Deadlock.
3Nested thread pool tasks: task submits subtask to same pool, pool full, subtask queued forever.
← Back to What is Deadlock? Overview