Lock Ordering and Deadlock Prevention
What you'll learn: How to prevent deadlock by establishing a consistent order in which threads acquire multiple locks.
The Deadlock Problem with Multiple Locks
When threads need to acquire multiple locks to complete their work, a dangerous situation can arise. Imagine thread A locks resource 1 and waits for resource 2, while thread B locks resource 2 and waits for resource 1. Both threads are now stuck forever—this is deadlock.
The Lock Ordering Solution
The simplest and most effective prevention strategy is to establish a global lock ordering—a rule that all threads must acquire locks in the same predetermined sequence.
How It Works
If you have locks L1, L2, and L3, enforce a rule: always lock them in alphabetical/numerical order (L1 → L2 → L3). Every thread in your program must follow this order, no exceptions.
Why this prevents deadlock: If thread A acquires L1 and thread B also needs L1, thread B must wait for A to release it. Thread B can never "jump ahead" and lock L2 first, creating a circular wait. The consistent ordering breaks the cycle that causes deadlock.
Practical Example
Think of it like a library checkout policy: books must be checked out in catalog number order. If you need books #42 and #89, you must check out #42 first. This prevents two students from deadlocking by each holding one book the other needs.
In code terms: if you need both accountLock and transferLock, always acquire accountLock first—everywhere in your program.
Key Takeaway: Deadlock can be prevented by establishing a global lock ordering and ensuring all threads acquire multiple locks in the exact same sequence, eliminating circular wait conditions.