在Java中,如果在并发中执行`insert()`和`size()`,是否存在死锁?

时间:2015-04-23 07:23:01

标签: java multithreading concurrency locking

代码如下所示(link):

/***
 * Excerpted from "Seven Concurrency Models in Seven Weeks",
***/
import java.util.concurrent.locks.ReentrantLock;

class ConcurrentSortedList {

  private class Node {
    int value;
    Node prev;
    Node next;
    ReentrantLock lock = new ReentrantLock();

    Node() {}

    Node(int value, Node prev, Node next) {
      this.value = value; this.prev = prev; this.next = next;
    }
  }

  private final Node head;
  private final Node tail;

  public ConcurrentSortedList() {
    head = new Node(); tail = new Node();
    head.next = tail; tail.prev = head;
  }

  public void insert(int value) {
    Node current = head;
    current.lock.lock(); 
    Node next = current.next;
    try {
      while (true) {
        next.lock.lock(); 
        try {
          if (next == tail || next.value < value) { 
            Node node = new Node(value, current, next); 
            next.prev = node;
            current.next = node;
            return; 
          }
        } finally { current.lock.unlock(); } 
        current = next;
        next = current.next;
      }
    } finally { next.lock.unlock(); } 
  }

  public int size() {
    Node current = tail;
    int count = 0;

    while (current.prev != head) {
      ReentrantLock lock = current.lock;
      lock.lock();
      try {
        ++count;
        current = current.prev;
      } finally { lock.unlock(); }
    }

    return count;
  }

}

它说它使用手动锁定insert()从列表头部到列表尾部锁定,size()从列表尾部锁定到列表头部。 size()insert()可以并发执行。

但我认为size()insert()不能在并发中执行。因为如果insert持有aNode上的锁定并请求锁定aNode.next,则size持有aNode.next上的锁并请求{ {1}},会出现僵局。

有没有人有这方面的想法?谢谢!

1 个答案:

答案 0 :(得分:2)

我看到.. size()会在请求新锁之前释放当前锁..所以不会出现死锁..