-1

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?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
idolice
  • 3
  • 2
  • An empty `FOR cycle` is actually an infinite loop. There are no command variables, no exit rule and evolution for the command var(s). It's the equivalent of `while(true) { ...};` – dbl Oct 10 '18 at 09:41
  • Your example wouldn't compile, as you have a couple of paths (the first `if`, and what happens if none of the outer conditions are satisfied) that don't return anything. It's a way to do a recursive task using an iterative approach. – Federico klez Culloca Oct 10 '18 at 09:43

2 Answers2

1

The syntax is used to say that what is inside will be executed an infinite amount of times. It is the same as:

while(true){..}

It means that inside there must be a statement that breaks this infinite execution which can be a break or return.

In your case that's a return statement, and the infinite loop is used to perform the same task until you reach the condition to meet the return. This is only valid if there is a progress/change in the state which is used to check the exit condition. In this case the change happens by following the links in a linked list data structure.

NiVeR
  • 9,644
  • 4
  • 30
  • 35
0

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.

landru27
  • 1,654
  • 12
  • 20