I found this code segment about concurrent linked queue in IBM Developer.
But I can't understand a part of them. Which is
while(true){
...
if(curTail == Tail.get()){
if(residue == null){
...
}
}
}
According to the define of curTail and residue, I think curTail is a copy of Tail and curTail is a pointer equals Tail.next .
I concern that function compareAndSet will judge if the caller object is equal to the first param, why must judge them before call this function? I think the code below can so the same thing well.
while (true) {
Node<E> curTail = tail.get();
Node<E> residue = curTail.next.get();
if (curTail.next.compareAndSet(null, newNode)) /* C */ {
tail.compareAndSet(curTail, newNode) /* D */ ;
return true;
} else {
tail.compareAndSet(curTail, residue) /* B */;
}
}
}
Any help would be appreciated. Thanks.
public class LinkedQueue <E> {
private static class Node <E> {
final E item;
final AtomicReference<Node<E>> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = new AtomicReference<Node<E>>(next);
}
}
private AtomicReference<Node<E>> head
= new AtomicReference<Node<E>>(new Node<E>(null, null));
private AtomicReference<Node<E>> tail = head;
public boolean put(E item) {
Node<E> newNode = new Node<E>(item, null);
while (true) {
Node<E> curTail = tail.get();
Node<E> residue = curTail.next.get();
if (curTail == tail.get()) {
if (residue == null) /* A */ {
if (curTail.next.compareAndSet(null, newNode)) /* C */ {
tail.compareAndSet(curTail, newNode) /* D */ ;
return true;
}
} else {
tail.compareAndSet(curTail, residue) /* B */;
}
}
}
}
}