Java Concurrency in Practice 读书笔记 第十章

粗略看完《Java Concurrency in Practice》这部书,确实是多线程/并发编程的一本好书。里面对各种并发的技术解释得比较透彻,虽然是面向Java的,但很多概念在其他语言的并发编程中,也可以用到。因此,开始写下其读书笔记,归纳总结。

 

闲话少说,从第十章开始,先上思维导图:

 

 

 

本章的重点,是死锁以及死锁的分析和避免方法

10.1.1 锁的顺序产生死锁:

public class WorkerThread implements Runnable{

    private LeftRightDeadlock lock;
    private boolean isLeft;
    
    public WorkerThread(LeftRightDeadlock lock, boolean isLeft) {
      super();
      this.lock = lock;
      this.isLeft = isLeft;
    }

    @Override
    public void run() {
      if(isLeft){
          lock.leftRight();
      }else{
          lock.rightLeft();
      }
    }

}
public class LeftRightDeadlock {

    private final Object leftLock = new Object();
    private final Object rightLock = new Object();

    public void leftRight() {
    System.out.println("left acquiring lock on leftLock");
    synchronized (leftLock) {
        System.out
            .println("left acquired lock on leftLock, acquiring lock on rightLock");
        sleep(); // key.
        synchronized (rightLock) {
        System.out.println("left is Working...");
        }
    }
    }

    public void rightLeft() {
    System.out.println("right acquiring lock on rightLock");
    synchronized (rightLock) {
        System.out
            .println("right acquired lock on rightLock, acquiring lock on leftLock");
        sleep(); // key.
        synchronized (leftLock) {
        System.out.println("right is Working...");

        }
    }
    }

    private void sleep() {
    try {
        TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
    LeftRightDeadlock lock = new LeftRightDeadlock();
    Thread thread1 = new Thread(new WorkerThread(lock, true));
    Thread thread2 = new Thread(new WorkerThread(lock, false));
    thread1.start();
    thread2.start();
    }

}

 

上述代码中,输出有可能是:

left acquiring lock on leftLock
right acquiring lock on rightLock
left acquired lock on leftLock, acquiring lock on rightLock
right acquired lock on rightLock, acquiring lock on leftLock

然后就死锁了。死锁的原因就在于两个线程试图经过不同的顺序取得相同的锁(The deadlock in LeftRightDeadlock came about because the two threads attempted to acquire the same locks in a different order):

thread1 -> lock left -> try to lock right -> wait forever

thread2       -> lock right -> try to lock left -> wait forever

 

 

10.1.2 动态锁的顺序产生死锁: 

public void transferMoney(Account fromAccount, Account toAccount,
        BigDecimal amount) throws Exception {

    synchronized (fromAccount) {
        synchronized (toAccount) {
        if(fromAccount.getBalance().compareTo(amount)<0){
            throw new Exception("Not enough money!!!");
        }else{
            fromAccount.debit(amount);
            toAccount.credit(amount);
        }
        }
    }

    }

假设有两个线程,分别调用:

transferMoney(myAccount, yourAccount, 10); 
transferMoney(yourAccount, myAccount, 20); 

同样,transferMoney会发生死锁。原因与10.1.1类似,都是内嵌锁导致死锁,只不过这里隐蔽一点,因为锁fromAccount和锁toAccount是动态的。为了解决这个问题,我们必须制定锁的顺序,并且在程序中,获得锁的顺序始终遵守这个约定。

一个制定锁顺序的方法是,利用锁的hashCode确定顺序。如果两个锁的hashCode刚好相等,便引入第三个tie-breaking锁,以保证只有一个线程以未知顺序获得锁:

 1 private static final Object tieLock = new Object();
 2     
 3     public void transferMoney2(Account fromAccount, Account toAccount,
 4         BigDecimal amount) throws Exception {
 5     
 6     int fromHash = System.identityHashCode(fromAccount);
 7     int toHash = System.identityHashCode(toAccount);
 8     
 9     if(fromHash<toHash){
10         synchronized (fromAccount) {
11           synchronized (toAccount) {
12               if(fromAccount.getBalance().compareTo(amount)<0){
13                 throw new Exception("Not enough money!!!");
14               }else{
15                 fromAccount.debit(amount);
16                 toAccount.credit(amount);
17               }
18           }
19         }
20     }else if(toHash<fromHash){
21         synchronized (toAccount) {
22           synchronized (fromAccount) {
23               if(fromAccount.getBalance().compareTo(amount)<0){
24                 throw new Exception("Not enough money!!!");
25               }else{
26                 fromAccount.debit(amount);
27                 toAccount.credit(amount);
28               }
29           }
30         }
31     }else{
32         synchronized (tieLock) {
33           synchronized (fromAccount) {
34               synchronized (toAccount) {
35                 if(fromAccount.getBalance().compareTo(amount)<0){
36                     throw new Exception("Not enough money!!!");
37                   }else{
38                     fromAccount.debit(amount);
39                     toAccount.credit(amount);
40                   }
41               }
42           }
43         }
44     }
45     
46     }

 

上述代码看起来有些臃肿,但基本的思路就是,利用hashCode,制定了根据hashCode,由小到大获得锁的规则,来解决死锁的问题。当然,如果hashCode经常冲突的话,就必须使用tieLock,那么这里就会成为并发的瓶颈。

假设Account具有一个唯一的,不可变的索引,那么制定锁的顺序就不需要hashCode且省去tie-breaking锁。

 

 

10.1.3 协作对象间的死锁

对比起10.1.1和10.1.2的死锁情况, 协作对象间的死锁更不明显,更不容易被发现:

 1 public class Taxi {
 2     
 3     private Point location, destination;
 4     private final Dispatcher dispatcher;
 5     
 6     public Taxi(Dispatcher dispatcher){
 7       this.dispatcher = dispatcher;
 8     }
 9     
10     public synchronized Point getLocation(){
11       return location;
12     }
13     
14     public synchronized void setLocation(Point location){
15       this.location = location;
16       if(location.equals(destination)){
17           dispatcher.notifyAvailable(this);
18       }
19     }
20     
21 }
22 
23 public class Dispatcher {
24     
25     private final Set<Taxi> taxis;
26     private final Set<Taxi> availableTaxis;
27     
28     public Dispatcher(){
29       taxis = new HashSet<Taxi>();
30       availableTaxis = new HashSet<Taxi>();
31     }
32     
33     public synchronized void notifyAvailable(Taxi taxi){
34       availableTaxis.add(taxi);
35     }
36     
37     public synchronized Image getImage(){
38       Image image = new Image();
39       for (Taxi t: taxis){
40           image.drawMarker(t.getLocation());
41       }
42     return image;
43     }
44     
45     
46 }

尽管没有方法显式地获得两个锁,但是也有可能出现死锁。原因如下:如果一个线程调用setLocation,检查已到达目的地,然后调用Dispatcher的notifyAvailable方法。由于setLocation和notifyAvailable都是synchronized方法,setLocation会获得Taxi的锁,而notifyAvailable会获得Dispatcher的锁;这时如果有线程调用getImage取得Dispatcher的锁,然后因为getImage里面的getLocation取得Taxi的锁,那么此时,两个锁被两个线程以不同的顺序占有,继而产生死锁风险。

 

所以,在持有锁的方法内,调用外部方法(alien method),则是产生死锁的一种警示。

 

 

10.1.4 开放调用:调用没有持有锁的方法。

使用开放调用,来解决协作间对象的死锁风险。通过减少synchronized块的使用,仅仅守护那些调用共享状态的操作,Taxi和Dispatcher可以被重构到使用开放调用,减少死锁风险。请看修改后的方法:

//Taxi
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);
    }
}


//Dispatcher
public synchronized void notifyAvailable(Taxi taxi){
    availableTaxis.add(taxi);
}
    
    
public Image getImage(){
    Set<Taxi> copy;
    synchronized (this) {
        copy = new HashSet<Taxi>(taxis);
    }
    Image image = new Image();
    for (Taxi t: copy){
        image.drawMarker(t.getLocation());
    }
    return image;
}

 

要注意的是,这样的重构会将一个操作(如getImage)由原子操作变为非原子操作。必须仔细考虑这样的损失是否可以接受。

 

 

10.2 避免和诊断死锁。

大概来说有几个方法:

1.避免内嵌锁。内嵌锁是最常见的产生死锁的原因。上述的10.1.1、10.1.2、10.1.3本质上都是由于内嵌锁而导致死锁。

2.需要的时候才加锁(Lock Only What is Required)。可参考10.1.4

3.避免无限时地等待。此时可以利用定时锁tryLock

4.分析thread dump。至于如何分析,之后再补充。

 

 

 

参考:《Java Concurrency In Practice》

posted @ 2013-09-18 16:10  macemers  阅读(1218)  评论(1编辑  收藏  举报