我试图在Java中使用ReentrantLock实现手动锁定,这是在LinkedList的Node类中初始化的,但我似乎有死锁我不知道如何解决它。任何帮助,将不胜感激。解决在Java中手动锁定链接列表中的死锁
// Insert value for key.
public boolean add(K key, V value) {
// Require key != null and value != null
// Get hash code
int hash = key.hashCode();
Node pred = null, curr = null;
try {
pred = head;
pred.lock.lock();
curr = pred.next;
curr.lock.lock();
while(curr.hash <= hash) {
if(key.equals(curr.key)) { // key present, update value
curr.value = value;
return false;
}
pred = curr;
pred.lock.lock();
curr = curr.next;
curr.lock.lock();
}
// key not present
Node node = new Node(hash, key, value);
node.next = pred.next;
pred.next = node;
return true;
} finally {
curr.lock.unlock();
pred.lock.unlock();
}
}
// Remove key/value pair
public boolean remove(K key) {
// Require key != null
// Get hash code
int hash = key.hashCode();
Node pred = null, curr = null;
try {
// Predecessor node
pred = this.head;
pred.lock.lock();
//Current node
curr = pred.next;
curr.lock.lock();
// traversing list
while(curr.hash <= hash) {
if(key.equals(curr.key)) { // key present, update value
pred.next = curr.next;
return true;
}
pred.lock.unlock();
pred = curr;
curr = curr.next;
curr.lock.lock();
}
// key not found
return false;
}finally {
curr.lock.unlock();
pred.lock.unlock();
}
}
它看起来像是在while循环中锁定节点,并且您没有在添加方法中释放它们。 – hal
http://cs.oswego.edu/pipermail/concurrency-interest/2007-April/004076.html –