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

Visualizing the Circular Wait

Tracing thread execution and lock acquisition to see how circular dependencies form in deadlock scenarios.

Visualizing the Circular Wait

You'll learn how to trace thread execution and lock acquisition to see circular dependencies form in deadlock scenarios.

Understanding the Circle

Circular wait is the deadlock condition where threads form a closed chain of lock dependencies. To truly understand deadlock, you need to visualize this circle forming as threads execute and acquire locks.

The Mental Model

Imagine drawing arrows from threads to locks they're holding, and from locks they're waiting for back to the threads holding those locks. In a deadlock, these arrows form a complete loop:

Thread A → holds Lock1 → wants Lock2 → held by Thread B → wants Lock1 → held by Thread A ← back to start

This circular dependency is why no thread can proceed.

Tracing Execution Step-by-Step

Consider two threads executing concurrently:

Thread A:                          Thread B:
1. synchronized(lock1) {           1. synchronized(lock2) {
2.   // acquired lock1             2.   // acquired lock2
3.   synchronized(lock2) {         3.   synchronized(lock1) {
4.     // wants lock2              4.     // wants lock1

Execution timeline:

  • T1: Thread A acquires lock1
  • T2: Thread B acquires lock2 (different lock, succeeds)
  • T3: Thread A tries to acquire lock2 → BLOCKS (B holds it)
  • T4: Thread B tries to acquire lock1 → BLOCKS (A holds it)

Now both threads are stuck waiting for each other. The circle closes: A→lock1→B→lock2→A

Drawing this on paper or using a debugger to pause threads at their waiting points makes the circular dependency unmistakable.

Key Takeaway: Visualizing thread execution and lock dependencies as a graph reveals how circular wait forms — threads create a closed loop where each waits for a resource held by the next thread in the chain.