1、由于方法入参由外部传递而来,方法内部虽然对两个参数按照固定顺序进行加锁,但是由于外部传递时顺序的不可控,而产生锁顺序造成的死锁,即动态锁顺序死锁。
2、示例代码如下:
// Warning: deadlock-prone! public static void transferMoney(Account fromAccount, Account toAccount, DollarAmount amount) throws InsufficientFundsException { synchronized (fromAccount) { synchronized (toAccount) { if (fromAccount.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(); else { fromAccount.debit(amount); toAccount.credit(amount); } } } }
transferMoney方法的三个参数,转出账户,转入账户,金额,在方法内按照转出账户,转入账户的顺序进行了加锁处理,是否就可以避免死锁的发生了呢?但事实上结果并没有达到避免死锁发生的预期。因为锁的顺序取决于传递给transferMoney的参数顺序,而这些顺序是外部调度传入的。如果两个线程同时调用transferMoney方法,一个线程从A账户向B账户转账,另一个线程从B账户向A账户转账,那么会产生我们之前一节总结的锁顺序导致的死锁。
3、由于传入的对象顺序不可确定,所以应该使用确定的顺序来调用锁。使用System.identityHashCode方法获取Object.hashCode返回的值作为比较顺序的依据,假设hashCode一致,则采用加时赛的一个单独锁,保证同一时刻只有一个线程可以操作。
代码示例如下:
/** * InduceLockOrder * * Inducing a lock order to avoid deadlock * * @author Brian Goetz and Tim Peierls */ public class InduceLockOrder { private static final Object tieLock = new Object(); public void transferMoney(final Account fromAcct, final Account toAcct, final DollarAmount amount) throws InsufficientFundsException { class Helper { public void transfer() throws InsufficientFundsException { if (fromAcct.getBalance().compareTo(amount) < 0) throw new InsufficientFundsException(); else { fromAcct.debit(amount); toAcct.credit(amount); } } } int fromHash = System.identityHashCode(fromAcct); int toHash = System.identityHashCode(toAcct); if (fromHash < toHash) { synchronized (fromAcct) { synchronized (toAcct) { new Helper().transfer(); } } } else if (fromHash > toHash) { synchronized (toAcct) { synchronized (fromAcct) { new Helper().transfer(); } } } else { synchronized (tieLock) { synchronized (fromAcct) { synchronized (toAcct) { new Helper().transfer(); } } } } } interface DollarAmount extends Comparable<DollarAmount> { } interface Account { void debit(DollarAmount d); void credit(DollarAmount d); DollarAmount getBalance(); int getAcctNo(); } class InsufficientFundsException extends Exception { } }