[Java concurrent programming practice] -- AQS (4): CLH synchronization queue

Source: Internet
Author: User

[Java concurrent programming practice] -- AQS (4): CLH synchronization queue

In [Java concurrent programming practice] -- "J. U. C": CLH queue lock has been raised. The CLH queue in AQS is a kind of deformation of the CLH synchronization lock. It is transformed from two aspects: node Structure and node wait mechanism. The header and tail nodes are introduced in the structure. They point to the header and tail of the queue respectively, and attempts to obtain the lock, enter the queue, and release the lock are all related to the header and tail nodes, in addition, each node introduces the reference of the precursor node and subsequent nodes. The waiting mechanism is changed from the original spin to blocking wake-up. Its structure is as follows:

Now that we know its structure, let's look at its implementation. The acquire () method of AQS is called when the thread gets the lock. If the first attempt of this method to obtain the lock fails, the thread will be added to the CLH queue:

public final void acquire(int arg) {        if (!tryAcquire(arg) &&            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))            selfInterrupt();    }

AddWaiter:

private Node addWaiter(Node mode) {        Node node = new Node(Thread.currentThread(), mode);        Node pred = tail;        if (pred != null) {            node.prev = pred;            if (compareAndSetTail(pred, node)) {                pred.next = node;                return node;            }        }        enq(node);        return node;    }

This is the implementation of addWaiter (). Before clarifying this code, we should first look at a more important Node in the Node and CLH queue. The source code is as follows:

Static final class Node {/** thread canceled */static final int CANCELLED = 1;/** the successor thread of the current thread needs to be unpark (awakened) */static final int SIGNAL =-1;/** the thread (in the Condition sleep state) waits for Condition to wake up */static final int CONDITION =-2; /** SHARED lock */static final Node SHARED = new Node ();/** EXCLUSIVE lock */static final Node EXCLUSIVE = null; volatile int waitStatus; /** successor Node */volatile Node prev;/** successor Node */volatile Node next; volatile Thread thread; Node nextWaiter; final boolean isShared () {return nextWaiter = SHARED;}/** get the forward Node */final Node predecessor () throws NullPointerException {Node p = prev; if (p = null) throw new NullPointerException (); else return p;}/*** three constructors */Node () {} Node (Thread thread, Node mode) {this. nextWaiter = mode; this. thread = thread;} Node (Thread thread, int waitStatus) {this. waitStatus = waitStatus; this. thread = thread ;}}

 

In this source code, there are three values (CANCELLED, SIGNAL, and CONDITION). Note that the CLH queue nodes all have a status bit, which is closely related to the thread status:

CANCELLED = 1: Due to timeout or interruption, the node is set to canceled. When the canceled node is not involved in the competition, it will remain canceled and not changed to another State;

SIGNAL =-1: The successor node has been blocked and needs to be awakened;

CONDITION =-2: indicates that the node is in the CONDITION queue and is blocked because of waiting for a CONDITION;

0: the value of the newly created node is generally 0.

Column

When the thread tries to obtain the lock, if it fails, it needs to add the thread to the CLH queue. The main process in the column is to run tail to create a node, then, point the successor node of the node to the Old tail value. Note that there is a CAS operation in this process, and the spin method is used until the operation is successful. The Code is as follows:

for(;;){            Node t = tail;            node.prev = t;            if (compareAndSetTail(t, node)) {                t.next = node;                return t;            }        }

In fact, this code exists in the enq () method.

Columns

When the thread is locked, it needs to "column out". The main task of column out is to wake up its successor node (generally head node), so that all threads can proceed in an orderly manner:

Node h = head;            if (h != null && h.waitStatus != 0)                unparkSuccessor(h);            return true;
Cancel

If a node is canceled because the thread times out or is interrupted, the node will not participate in the lock competition and will wait for GC to recycle. The main process of cancellation is to remove the canceled node, and the process of removal is relatively simple. First, set the status to CANCELLED, and then run the pred of its precursor node on its successor node. Of course, this process will still be a CAS operation:

node.waitStatus = Node.CANCELLED;Node pred = node.prev;Node predNext = pred.next;Node next = node.next;
Pending

We understand that the CLH queue of AQS is compared to the original CLH queue lock. It adopts a deformation operation to change the spin mechanism to the blocking mechanism. The current thread first checks whether it is a header node and attempts to obtain the lock. If the current node is a header node and the lock is successfully obtained, the system returns directly. The current thread is not blocked; otherwise, the current thread is blocked:

For (;) {if (node. prev = head) if (the lock is successfully obtained) {head = node; node. next = null; return;} blocks the thread}

Reference

Java concurrency framework-AQS blocking Queue Management (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.