关于AQS框架中的addWaiter()方法有一点疑问。
作者: Sortinn创建于 2018年9月3日更新于 2022年9月19日
标签question
/**
- Creates and enqueues a node for the current thread and the 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 操作进行入队,自旋至入队成功才会退出。
内容来源: crossoverJie/JCSprout