Avoid Deadlock example

前端 未结 6 2111
谎友^
谎友^ 2020-12-13 04:51

I am wondering what are the alternative ways to avoid deadlock in the following example. The following example is a typical bank account transferring deadlock problem. What

6条回答
  •  死守一世寂寞
    2020-12-13 05:20

    Sort the accounts. The dead lock is from the ordering of the accounts (a,b vs b,a).

    So try:

     public static void transfer(Account from, Account to, double amount){
          Account first = from;
          Account second = to;
          if (first.compareTo(second) < 0) {
              // Swap them
              first = to;
              second = from;
          }
          synchronized(first){
               synchronized(second){
                    from.withdraw(amount);
                    to.deposit(amount);
               }
          }
     }
    

提交回复
热议问题