chapter10 避免活跃性危险

 

1、死锁
   JVM在解决死锁方面没有数据库那样强大,无法自动检测和处理死锁。往往只能通过中止并重启才能彻底恢复。
   1)顺序死锁
      
public   class  LeftRightDeadLock {

     final Object left =  new Object();
     final Object right =  new Object();

     public  void doLeftRight() {
         synchronized (left) {
             synchronized (right) {
                execute1();
            }
        }
    }

     public  void doRightLeft() {
         synchronized (right) {
             synchronized (left) {
                execute2();
            }
        }
    }

     private  void execute2() {
    }

     private  void execute1() {
    }
}

   2)动态锁顺序死锁
    看似无害的代码,例如将资金从账户A转移到账户B,实际上在出现并发的逆操作时(从账户B转到账户A),就可能会出现死锁。
     public   void  transferMoney(Account fromAccount, //
        Account toAccount, //
         int amount
        ) {
     synchronized (fromAccount) {
         synchronized (toAccount) {
            fromAccount.decr(amount);
            toAccount.add(amount);
        }
    }
}

   处理这种情况的办法是通过锁顺序来避免
    public class InduceLockOrder {
    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)
                    throw 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();
                    }
                }
            }
        }
    }

    interface DollarAmount extends Comparable<DollarAmount> {
    }

    interface Account {
        void debit(DollarAmount d);

        void credit(DollarAmount d);

        DollarAmount getBalance();

        int getAcctNo();
    }

    class InsufficientFundsException extends Exception {
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值