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){.
throws 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();
}
}
}
}
}
锁顺序避免死锁
最新推荐文章于 2024-04-08 22:47:07 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)