[Java concurrent programming practice] ----- "J. U. C": CLH queue lock
CLH queue is a queue that maintains a group of threads strictly in FIFO mode in AQS. He is able to ensure that there is no hunger and strict first-come Service Fairness. It is a CLH queue node:
The node QNode in the clh queue contains a locked field. This field indicates whether the node needs to obtain the lock. If it is set to true, it needs to be obtained. If it is set to false, it does not need to be obtained. In the CLH queue, nodes are not connected through the next pointer, but the behavior of myNode is affected by the changes in the node to which myPred points.
Assume there are two threads (thread A and thread B ). When thread A needs to obtain the lock, it will create A QNode node and set locked to true (indicating that the lock needs to be obtained ), at the same time, obtain a myPred pointing to the front-end and rotate it on the locked of the front-end node until the front-end node is locked (locked is false, which is generally called spin ), of course, tail points to itself to indicate that it is the last node of the CLH queue, as shown below:
Then thread B is added to the CLH queue, and the tail domain should point to thread B.
The advantage of CLH queue lock is its low space complexity (if there are n threads and L locks, each thread obtains only one lock at a time, the required storage space is O (L + n), n threads have n mynodes, and L locks have L tails ). CLH variants are used in AQS.