关于AQS框架中addWaiter()方法的一点疑问。

Author: SortinnCreated Sep 3, 2018Updated Sep 19, 2022
Labelsquestion
 /**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

在 addWaiter() 这个方法中,JDK 为何要先用一次 CAS 尝试将新的 node 添加到队尾,而不直接调用 enq() 方法来入队呢? enq() 方法的实现也是使用 CAS 操作入队,自旋至入队成功才会退出。

/**
     * Inserts node into queue, initializing if necessary. See picture above.
     * @param node the node to insert
     * @return node's predecessor
     */
    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;
                }
            }
        }
    }

并且两个方法存在一部分相同的代码,这样设计不会冗余吗?希望得到您的解答,谢谢~