R
Rishtaara
Operating Systems Fundamentals
Lesson 5 of 8Article17 min

Deadlocks and Synchronization Pitfalls

If all four conditions hold simultaneously, deadlock can happen. Breaking any one condition helps prevention.

Deadlock conditions

If all four conditions hold simultaneously, deadlock can happen. Breaking any one condition helps prevention.

  • Mutual exclusion
  • Hold and wait
  • No preemption
  • Circular wait

Simple lock ordering strategy

Acquire locks in fixed order
Object lockA = new Object();
Object lockB = new Object();

// Always acquire A then B in every thread.
synchronized (lockA) {
  synchronized (lockB) {
    // critical section
  }
}