title: Thread safe swapping in Java
body: <p>I have a method which receives two bank account as inputs and swap their values :</p>
  
  <pre><code>Public void TransferAccount(AccountID  id1, AccountID id2){
      Account a1 = id1.GetAccount();
      Account a2 = id2.GetAccount();
  
      //Swap amounts.
  
      Temp = a1.Balance;
      a1.Balance = a2.Balance;
      a2.Balance = Temp;
  }
  </code></pre>
  
  <p>I want to make this method to be thread-safe with the highest possible performance (I guess it means we may not make the method synchronized) , we have also to be careful about the deadlock ,</p>
  
  <p>I thought of the following solution : </p>
  
  <pre><code>Public void TransferAccount(AccountID  id1, AccountID id2){
      Account a1 = id1.GetAccount();
      Account a2 = id2.GetAccount();
  
  //Swap amounts.
      synchronized(a1){
          wait(a2);
          synchronized(a2){
              Temp = a1.Balance;
              a1.Balance = a2.Balance;
              a2.Balance = Temp;
          }
      }
  }
  </code></pre>
  
  <p>Is there any better implementation in terms of performance ? and by the way , is this thread-safe at all ?</p>