Vermeidung Deadlock-Beispiel

Frage ich mich, was sind die alternativen Möglichkeiten zur Vermeidung von Deadlocks in dem folgenden Beispiel. Das folgende Beispiel ist eine typische bank-Konto übertragen deadlock-problem. Was sind einige bessere Ansätze, es zu lösen in der Praxis ?

class Account {
     double balance;
     int id;
     public Account(int id, double balance){
          this.balance = balance;
          this.id = id;
     }
     void withdraw(double amount){
          balance -= amount;
     } 
     void deposit(double amount){
          balance += amount;
     }
}
class Main{
     public static void main(String [] args){
           final Account a = new Account(1,1000);
           final Account b = new Account(2,300);
           Thread a = new Thread(){
                 public void run(){
                     transfer(a,b,200);
                 }
           };
           Thread b = new Thread(){
                 public void run(){
                     transfer(b,a,300);
                 }
           };
           a.start();
           b.start();
     }
     public static void transfer(Account from, Account to, double amount){
          synchronized(from){
               synchronized(to){
                    from.withdraw(amount);
                    to.deposit(amount);
               }
          }
     }
}

Frage ich mich, wird es lösen die deadlock-Problem, wenn ich trennen Sie das verschachtelte sperren in meiner transfer-Methode wie im folgenden

 synchronized(from){
      from.withdraw(amount);
 }
 synchronized(to){
      to.deposit(amount);
 }
  • Dein Beispiel ist nicht klassische deadlock-Beispiel. Es immer Schloss sowohl das Konto für den gleichen thread, so dass kein deadlock auftreten wird. Wollten Sie diesen code in Ihre transfer-Methode : static void überweisen(Konto von, Konto nach, double Betrag) { synchronized(from) { aus.abheben(Betrag); synchronized(to) { to.Kaution(Betrag); } } }
InformationsquelleAutor peter | 2012-11-10
Schreibe einen Kommentar