[英]In Java, is there a deadlock if `insert()` and `size()` executed in concurrency?
代碼看起來像這樣( 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
上的鎖並請求aNode
上的鎖,則將出現死鎖。
有人對此有想法嗎? 謝謝!
我看到.. size()
將在請求新鎖之前釋放當前鎖。.因此不會出現死鎖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.