锁顺序避免死锁

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();
          }
        }
      }
   }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/118975797