when I read the AbstractQueuedSynchronize
source code, about the method
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
I'm wondering why there's a for loop since it could be like this:
private Node enq(final Node node) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
}
node.prev = tail;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
dose this have something todo with the concurrent?
Your re-write is not equivalent code. In your version, if the call to compareAndSetHead(new Node())
evaluates to false, tail
will still be null
at node.prev = tail;
The original, wrapped in the for (;;) { ... }
will keep trying until tail
is non-null
.