Skip to content
C

Deadlock

A deadlock happens when two or more threads are stuck waiting forever for each other to release a resource, with neither thread able to proceed — resulting in the program freezing for those threads.


1. What is Deadlock?

A deadlock happens when two or more threads are stuck waiting forever for each other to release a resource, with neither thread able to proceed — resulting in the program freezing for those threads.

2. Why is it used?

Understanding deadlocks isn't about "using" them intentionally — it's about recognizing how they happen so you can design your synchronized code to avoid this dangerous, frozen situation.

3. Real-Life Example

Think of two people, each holding one chopstick, both needing two chopsticks to eat. Person A refuses to give up their chopstick until they get the second one from Person B, and Person B does the same — neither ever eats, and both remain stuck forever.

4. Syntax

java
// Deadlock typically arises from this kind of pattern: synchronized(lockA) { synchronized(lockB) { // thread 1 does this } } // while another thread does: synchronized(lockB) { synchronized(lockA) { // thread 2 does this - opposite order causes deadlock risk } }

5. Example Program

java
public class DeadlockDemo { public static void main(String[] args) { final Object lockA = new Object(); final Object lockB = new Object(); Thread t1 = new Thread(() -> { synchronized (lockA) { synchronized (lockB) { System.out.println("Thread 1 acquired both locks"); } } }); Thread t2 = new Thread(() -> { synchronized (lockA) { synchronized (lockB) { System.out.println("Thread 2 acquired both locks"); } } }); t1.start(); t2.start(); } }

Output:

Thread 1 acquired both locks
Thread 2 acquired both locks

(This particular example uses a consistent lock order and completes safely — deadlock risk arises specifically when different threads acquire the same locks in different, conflicting orders.)

6. Key Points to Remember

  • Deadlock commonly happens when multiple locks are acquired in different, inconsistent orders by different threads.
  • A deadlocked program doesn't crash — it simply hangs forever for the affected threads.
  • Always acquiring locks in the exact same, consistent order across all threads is a common way to avoid deadlocks.