代码如下所示(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}},会出现僵局。
有没有人有这方面的想法?谢谢!
答案 0 :(得分:2)
我看到.. size()
会在请求新锁之前释放当前锁..所以不会出现死锁..