gpt4 book ai didi

java - Java中 `insert()`和 `size()`并发执行会出现死锁吗?

转载 作者:行者123 更新时间:2023-12-02 04:44:12 25 4
gpt4 key购买 nike

代码如下所示(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() 将在请求新锁之前释放当前锁.. 因此不会出现死锁..

关于java - Java中 `insert()`和 `size()`并发执行会出现死锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com