Doubts about the enq() CAS operation in AQS

private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            //If the queue is empty, create a new head node
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    //point tail to head node
                    tail = head;
            } else {
            	//1. Point the front pointer of the new node to the end of the linked list
                node.prev = t;
                //2. Point the reference of tail to node through CAS
                if (compareAndSetTail(t, node)) {
                    //3. Point the back pointer of the original tail node to the new node
                    t.next = node;
                    //Exit of the for loop
                    return t;
                }
            }
        }
    }

This is the method for the node to enter the synchronization queue. The CAS operation compareAndSetTail(t, node) is used to point the reference of tail to node. The content of parameter t is the old reference object address of tail, and node is the address of the new node. Let's take a look at the specific content of compareAndSetTail(t, node) in AQS,

private final boolean compareAndSetTail(Node expect, Node update) {
        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }
tailOffset = unsafe.objectFieldOffset
                (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));

The tailOffset here is the offset of the "tail" variable relative to the "starting address" of the Java object obtained by the method in the unsafe class, that is, the tailOffset can be approximated as the address of the tail. That is to say, the data at the address of the knowledge tail variable updated by the CAS operation will not modify the value of the local variable t. After compareAndSetTail(t, node) is executed, t still points to the original old chain tail, and tail points to the new node.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324737648&siteId=291194637