Course contentsShow
← Java
Lesson 2691 of 2,87049. Synchronization and LockingFree lesson

The Four Necessary Conditions for Deadlock

Understanding mutual exclusion, hold and wait, no preemption, and circular wait as prerequisites for deadlock.

The Four Necessary Conditions for Deadlock

What you'll learn: The four conditions that must all occur simultaneously for deadlock to happen in a multithreaded program.

Why This Matters

Understanding that deadlock requires all four conditions simultaneously is crucial — if you can break even one, you prevent deadlock entirely. This gives you concrete strategies for writing deadlock-free code.

The Four Necessary Conditions

Deadlock occurs if and only if all four of these conditions hold at the same time:

1. Mutual Exclusion

Resources (like synchronized locks) can only be held by one thread at a time. Other threads must wait. This is fundamental to synchronization — you can't eliminate this without losing thread safety.

2. Hold and Wait

A thread holds at least one lock while waiting to acquire another lock. It doesn't release what it has while waiting for more.

Analogy: You're holding a key to Room A but waiting for the key to Room B — you won't give up Room A's key while waiting.

3. No Preemption

Locks cannot be forcibly taken away from a thread. A thread must voluntarily release its locks. The system can't say "give up that lock now!"

4. Circular Wait

A circular chain exists: Thread T1 waits for a lock held by T2, T2 waits for a lock held by T3, ..., and eventually Tn waits for a lock held by T1. The cycle closes.

Analogy: Four people at a four-way stop, each waiting for the person on their right to go first — nobody can proceed.

Why All Four?

Remove any one condition and deadlock becomes impossible. For example:

  • Eliminate hold-and-wait by acquiring all locks at once
  • Prevent circular wait by always acquiring locks in the same global order
  • Allow preemption (though Java's intrinsic locks don't support this)

Key Takeaway: Deadlock requires all four conditions — mutual exclusion, hold and wait, no preemption, and circular wait — to occur simultaneously. Breaking even one prevents deadlock.