java中常见的死锁以及解决方法代码
在java中我们常常使用加锁机制来确保线程安全,但是如果过度使用加锁,则可能导致锁顺序死锁。同样,我们使用线程池和信号量来限制对资源的使用,但是这些被限制的行为可能会导致资源死锁。java应用程序无法从死锁中恢复过来,因此设计时一定要排序那些可能导致死锁出现的条件。
1.一个最简单的死锁案例
当一个线程永远地持有一个锁,并且其他线程都尝试获得这个锁时,那么它们将永远被阻塞。在线程a持有锁l并想获得锁m的同时,线程b持有锁m并尝试获得锁l,那么这两个线程将永远地等待下去。这种就是最简答的死锁形式(或者叫做"抱死")。
2.锁顺序死锁
如图:leftright和rightleft这两个方法分别获得left锁和right锁。如果一个线程调用了leftright,而另一个线程调用了rightleft,并且这两个线程的操作是交互执行,那么它们就会发生死锁。
死锁的原因就是两个线程试图以不同的顺序来获得相同的锁。所以,如果所有的线程以固定的顺序来获得锁,那么在程序中就不会出现锁顺序死锁的问题。
2.1.动态的锁顺序死锁
我以一个经典的转账案例来进行说明,我们知道转账就是将资金从一个账户转入另一个账户。在开始转账之前,首先需要获得这两个账户对象得锁,以确保通过原子方式来更新两个账户中的余额,同时又不破坏一些不变形条件,例如 账户的余额不能为负数。
所以写出的代码如下:
//动态的锁的顺序死锁 public class dynamicorderdeadlock { public static void transfermoney(account fromaccount,account toaccount,int amount,int from_index,int to_index) throws exception { system.out.println("账户 "+ from_index+"~和账户~"+to_index+" ~请求锁"); synchronized (fromaccount) { system.out.println(" 账户 >>>"+from_index+" <<<获得锁"); synchronized (toaccount) { system.out.println(" 账户 "+from_index+" & "+to_index+"都获得锁"); if (fromaccount.compareto(amount) < 0) { throw new exception(); }else { fromaccount.debit(amount); toaccount.credit(amount); } } } } static class account { private int balance = 100000;//这里假设每个人账户里面初始化的钱 private final int accno; private static final atomicinteger sequence = new atomicinteger(); public account() { accno = sequence.incrementandget(); } void debit(int m) throws interruptedexception { thread.sleep(5);//模拟操作时间 balance = balance + m; } void credit(int m) throws interruptedexception { thread.sleep(5);//模拟操作时间 balance = balance - m; } int getbalance() { return balance; } int getaccno() { return accno; } public int compareto(int money) { if (balance > money) { return 1; }else if (balance < money) { return -1; }else { return 0; } } } }
public class demonstratedeadlock { private static final int num_threads = 5; private static final int num_accounts = 5; private static final int num_iterations = 100000; public static void main(string[] args) { final random rnd = new random(); final account[] accounts = new account[num_accounts]; for(int i = 0;i < accounts.length;i++) { accounts[i] = new account(); } class transferthread extends thread{ @override public void run() { for(int i = 0;i < num_iterations;i++) { int fromacct = rnd.nextint(num_accounts); int toacct =rnd.nextint(num_accounts); int amount = rnd.nextint(100); try { dynamicorderdeadlock.transfermoney(accounts[fromacct],accounts[toacct], amount,fromacct,toacct); //inducelockorder.transfermoney(accounts[fromacct],accounts[toacct], amount); //inducelockorder2.transfermoney(accounts[fromacct],accounts[toacct], amount); }catch (exception e) { system.out.println("发生异常-------"+e); } } } } for(int i = 0;i < num_threads;i++) { new transferthread().start(); } } }
打印结果如下:
注意:这里的结果是我把已经执行完的给删除后,只剩下导致死锁的请求.
//通过锁顺序来避免死锁 public class inducelockorder { private static final object tielock = new object(); public static void transfermoney(final account fromacct, final account toacct, final int amount) throws exception { class helper { public void transfer() throws exception { if (fromacct.compareto(amount) < 0) { throw new exception(); } 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(); } } } } } static class account { private int balance = 100000; public account() { } void debit(int m) throws interruptedexception { thread.sleep(5); balance = balance + m; } void credit(int m) throws interruptedexception { thread.sleep(5); balance = balance - m; } int getbalance() { return balance; } public int compareto(int money) { if (balance > money) { return 1; }else if (balance < money) { return -1; }else { return 0; } } } }
经过我测试,此方案可行,不会造成死锁。
方案二
在account中包含一个唯一的,不可变的,值。比如说账号等。通过对这个值对对象进行排序。
具体代码如下
public class inducelockorder2 { public static void transfermoney(final account fromacct, final account toacct, final int amount) throws exception { class helper { public void transfer() throws exception { if (fromacct.compareto(amount) < 0) { throw new exception(); } else { fromacct.debit(amount); toacct.credit(amount); } } } int fromhash = fromacct.getaccno(); int tohash = toacct.getaccno(); if (fromhash < tohash) { synchronized (fromacct) { synchronized (toacct) { new helper().transfer(); } } } else if (fromhash > tohash) { synchronized (toacct) { synchronized (fromacct) { new helper().transfer(); } } } } static class account { private int balance = 100000; private final int accno; private static final atomicinteger sequence = new atomicinteger(); public account() { accno = sequence.incrementandget(); } void debit(int m) throws interruptedexception { thread.sleep(6); balance = balance + m; } void credit(int m) throws interruptedexception { thread.sleep(6); balance = balance - m; } int getbalance() { return balance; } int getaccno() { return accno; } public int compareto(int money) { if (balance > money) { return 1; }else if (balance < money) { return -1; }else { return 0; } } } }
经过测试此方案也可行。
2.2在协作对象之间发生的死锁
如果在持有锁时调用某外部的方法,那么将出现活跃性问题。在这个外部方法中可能会获取其他的锁(这个可能产生死锁),或阻塞时间过长,导致其他线程无法及时获得当前持有的锁。
场景如下:taxi代表出租车对象,包含当前位置和目的地。dispatcher代表车队。当一个线程收到gps更新事件时掉用setlocation,那么它首先更新出租车的位置,然后判断它是否到达目的地。如果已经到达,它会通知dispatcher:它需要一个新的目的地。因为setlocation和notifyavailable都是同步方法,因此掉用setlocation线程首先获取taxi的锁,然后在获取dispatcher的锁。同样,掉用getimage的线程首先获取dispatcher的锁,再获取每一个taxi的锁,这两个线程按照不同的顺序来获取锁,因此可能导致死锁。
能造成死锁的代码如下:
//会发生死锁 public class cooperatingdeadlock { // 坐标类 class point { private final int x; private final int y; public point(int x, int y) { this.x = x; this.y = y; } public int getx() { return x; } public int gety() { return y; } } // 出租车类 class taxi { private point location, destination; private final dispatcher dispatcher; public taxi(dispatcher dispatcher) { this.dispatcher = dispatcher; } public synchronized point getlocation() { return location; } public synchronized void setlocation(point location) { this.location = location; if (location.equals(destination)) { dispatcher.notifyavailable(this); } } public synchronized point getdestination() { return destination; } public synchronized void setdestination(point destination) { this.destination = destination; } } class dispatcher { private final set<taxi> taxis; private final set<taxi> availabletaxis; public dispatcher() { taxis = new hashset<>(); availabletaxis = new hashset<>(); } public synchronized void notifyavailable(taxi taxi) { availabletaxis.add(taxi); } public synchronized image getimage() { image image = new image(); for(taxi t:taxis) { image.drawmarker(t.getlocation()); } return image; } } class image{ public void drawmarker(point p) { } } }
解决方案:使用开放掉用。
如果再调用某个方法时不需要持有锁,那么这种调用就被称为开放掉用。这种调用能有效的避免死锁,并且易于分析线程安全。
修改后的代码如下:
//此方案不会造成死锁 public class cooperatingnodeadlock { // 坐标类 class point { private final int x; private final int y; public point(int x, int y) { this.x = x; this.y = y; } public int getx() { return x; } public int gety() { return y; } } // 出租车类 class taxi { private point location, destination; private final dispatcher dispatcher; public taxi(dispatcher dispatcher) { this.dispatcher = dispatcher; } public synchronized point getlocation() { return location; } public void setlocation(point location) { boolean reacheddestination; synchronized (this) { this.location = location; reacheddestination = location.equals(destination); } if (reacheddestination) { dispatcher.notifyavailable(this); } } public synchronized point getdestination() { return destination; } public synchronized void setdestination(point destination) { this.destination = destination; } } class dispatcher { private final set<taxi> taxis; private final set<taxi> availabletaxis; public dispatcher() { taxis = new hashset<>(); availabletaxis = new hashset<>(); } public synchronized void notifyavailable(taxi taxi) { availabletaxis.add(taxi); } public image getimage() { set<taxi> copy; synchronized (this) { copy = new hashset<>(taxis); } image image = new image(); for(taxi t:copy) { image.drawmarker(t.getlocation()); } return image; } } class image{ public void drawmarker(point p) { } } }
总结:活跃性故障是一个非常严重的问题,因为当出现活跃性故障时,除了终止应用程序之外没有其他任何机制可以帮助从这种故障中恢复过来。最常见的活跃性故障就是锁顺序死锁。在设计时应该避免产生顺序死锁:确保线程在获取多个锁时采用一直的顺序。最好的解决方案是在程序中始终使用开放掉用。这将大大减小需要同时持有多个锁的地方,也更容易发现这些地方。
以上所述是小编给大家介绍的java中常见的死锁以及解决方法详解整合,希望对大家有所帮助