Avoid Deadlock example

前端 未结 6 1996
谎友^
谎友^ 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

    In addition to the solution of lock ordered you can also avoid the deadlock by synchronizing on a private static final lock object before performing any account transfers.

     class Account{
     double balance;
     int id;
     private static final Object lock = new Object();
      ....
    
    
    
    
     public static void transfer(Account from, Account to, double amount){
              synchronized(lock)
              {
                        from.withdraw(amount);
                        to.deposit(amount);
              }
         }
    

    This solution has the problem that a private static lock restricts the system to performing transfers "sequentially".

    Another one can be if each Account has a ReentrantLock:

    private final Lock lock = new ReentrantLock();
    
    
    
    
    public static void transfer(Account from, Account to, double amount)
    {
           while(true)
            {
              if(from.lock.tryLock()){
                try { 
                    if (to.lock.tryLock()){
                       try{
                           from.withdraw(amount);
                           to.deposit(amount);
                           break;
                       } 
                       finally {
                           to.lock.unlock();
                       }
                    }
               }
               finally {
                    from.lock.unlock();
               }
    
               int n = number.nextInt(1000);
               int TIME = 1000 + n; // 1 second + random delay to prevent livelock
               Thread.sleep(TIME);
            }
    
     }
    

    Deadlock does not occur in this approach because those locks will never be held indefinitely. If the current object's lock is acquired but the second lock is unavailable, the first lock is released and the thread sleeps for some specified amount of time before attempting to reacquire the lock.

提交回复
热议问题