Lock Ordering Avoids Deadlock
Order lock acquisition by account id so opposite-direction transfers queue on the same locks instead of holding one and waiting for the other forever.
Code
import java.util.concurrent.locks.ReentrantLock;
public class TransferOrders {
record Account(long id, ReentrantLock lock) {}
static final Account ALICE = new Account(1, new ReentrantLock());
static final Account BOB = new Account(2, new ReentrantLock());
// 死锁根源:两个线程以相反顺序拿两把锁,各自持有一把再等对方。
// 修复:全系统约定一致的加锁顺序(这里按账户 id 升序),只能排队不能成环
static void transfer(Account from, Account to, int amount) {
ReentrantLock first = from.id() < to.id() ? from.lock() : to.lock();
ReentrantLock second = first == from.lock() ? to.lock() : from.lock();
first.lock();
try {
second.lock();
try {
System.out.println("moved " + amount + " from id " + from.id()
+ " to id " + to.id());
} finally {
second.unlock();
}
} finally {
first.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
// 方向相反的两笔转账:一致的顺序让它们排队而非互相等待
Thread one = new Thread(() -> transfer(ALICE, BOB, 10));
Thread two = new Thread(() -> transfer(BOB, ALICE, 5));
one.start();
two.start();
one.join(2000);
two.join(2000);
System.out.println("both finished, no deadlock: "
+ (one.getState() != Thread.State.BLOCKED
&& two.getState() != Thread.State.BLOCKED));
}
}Reading the snippet
The snippet is organized around the classes TransferOrders and Account and the function transfer.
What to watch for
- Any imports it has resolve to standard-library modules.
Applying it
The callable you reach for: static void transfer(Account from, Account to, int amount)
The run emits 2 labeled sections — moved, both finished, no deadlock: — one per step.
There are 1 call inside main — transfer — executed top to bottom.
Statements that matter
Thread one = new Thread(() -> transfer(ALICE, BOB, 10));
Thread two = new Thread(() -> transfer(BOB, ALICE, 5));
+ (one.getState() != Thread.State.BLOCKED
&& two.getState() != Thread.State.BLOCKED));
Interactive Tools for This Topic
FAQ
- What does Lock Ordering Avoids Deadlock print when run?
- Execute the whole file; each printed line is prefixed with a label like `moved`, `both finished, no deadlock:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.