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

What Is Deadlock?

Defining deadlock: a circular waiting condition where threads block each other indefinitely, preventing progress.

What You'll Learn

You'll learn what deadlock is: a critical concurrency bug where two or more threads become permanently stuck, each waiting for the other to release a lock.


The Problem

Imagine two people trying to pass through a narrow doorway, each politely waiting for the other to go first—forever. Neither moves, and both are stuck indefinitely. In multithreaded Java programs, deadlock occurs when threads enter a similar standoff with locks.

Deadlock happens when:

  1. Thread A holds Lock 1 and waits for Lock 2
  2. Thread B holds Lock 2 and waits for Lock 1
  3. Neither can proceed because each needs what the other holds

This creates a circular waiting condition: A waits for B, B waits for A, forming a cycle with no exit.

Why It Matters

Unlike race conditions (where threads compete unpredictably), deadlock causes threads to stop making progress entirely. The program appears to hang, consuming CPU cycles in a blocked state but accomplishing nothing. The JVM cannot automatically detect or break deadlocks—your application simply freezes.

The Circular Dependency

Deadlock requires multiple locks and an unfortunate ordering. When threads acquire locks in different sequences, they risk meeting in the middle: each holding one resource the other needs. The "circular" nature means the dependency chain loops back on itself, creating an unbreakable waiting cycle.

This typically occurs with:

  • Two or more synchronized blocks or methods
  • Different lock acquisition orders in different code paths
  • No timeout mechanism or escape route

Key Takeaway: Deadlock is a circular waiting condition where threads block each other indefinitely by holding locks and waiting for locks the others possess, preventing all involved threads from making progress.