Java concurrency--Concurrency basics

Source: Internet
Author: User
Tags cas prev

On the basis of concurrency, the main understanding of CAs and AQS. CAS:Compare and swap compare then swap AQS: Abstractqueuedsynchronizer-Abstract Queue Synchronizer First, CASThe  cas is used in many non-locking concurrency. Lock-free concurrency means that concurrent operations are implemented in a non-locking manner, and this wave operation is not very 666. The usual lock-up operation (either synchronized or lock) is a pessimistic view of the locked part (whether object, method, or block of code) each operation will cause competition for resources. CAS is more optimistic, he believes that access to resources is not a conflict, since there is no conflict should be a friendly visit. All access threads do not need to stop to wait for other threads to release resources when they come to this piece.   Where is the optimism of CAs? is by comparing and then exchanging ideas.  cas algorithm: contains three parameters (V,e,n), where V represents the variable to be updated, E represents the expected variable, and n represents the new value. When and only if the V value equals the E value, the V value is updated to the N value. and returns the V value.   On a thread L, he was going to update a value (V), he first knew that the value should be equal to E, before the update he first to compare, when the confirmation V is equal to E, he thought that the value is not modified by other threads, blue, and then update to V, updated to the N value. One of the applications of  cas is the atomic package for the JDK. For example, Atomicinteger compareandset is the primary method used when  public final boolean compareandset (int expect, int update) { & Nbsp;  return Unsafe.compareandswapint (This, valueoffset, expect, update);} The  compareandswapint method of  unsafe is native and will invoke the underlying operating system to complete the modification of the value   cas will encounter an unresolved problem, the ABA issue. The V value is modified several times in processing. This means that for the previous thread L, he went to update the V value. Confirming that the V value equals e cannot fully confirm that the value has not been modified by another thread. For example, thread L1 changes the V value to V1, and the thread L2 changes the V value back to the V value. The V value has undergone two modifications, but for L threads, this value has not been modified. The But,v value is actually updated several times.   for ABA problems, the solution is to set a timestamp and update the timestamp each time the modification succeeds. The V value is updated when both the expected value of the V value and the expected time stamp are met.    Second, AQSAqs is the Abstractqueuedsynchronizer class under the Java.util.concurrent.locks package. Aqs Core is the state of synchronization through shared variables, the state of variables is maintained by subclasses, the AQS framework mainly does: Thread blocking queue maintenance thread blocking and wake up* <pre>* +------+ prev +-----+ +-----+* head | |          <----| |          <----| | Tail*         +------+         +-----+          +-----+* </pre>Excerpt from the JDK source code is a description of the LCH queue lock. The LCH queue Lock is a FIFO queue, where each node is a waiting thread and its pre-secondary node (pre) releases the lock before it can get the lock. Abstractqueuedsynchronizer maintains this queue through internal class node. The Abstractqueuedsynchronizer member variable maintains a node-type head, a node-type tail, and a status state. Maintains queue-out operations for LCH queues and changes to state status. The modification of the shared variable state is done through the CAS of unsafe.    Protected Final Boolean compareandsetstate (int expect, int update) {//See below for intrinsics setup to Return Unsafe.compareandswapint (this, stateoffset, expect, update);}/*** Create a node node with the current thread and the specified pattern, and queue the nodes** @param mode node.exclusive for EXCLUSIVE (exclusive mode, only one thread can execute, such as Reetrantlock), node.shared for Shared (shared mode, multiple threads can execute simultaneously, e.g. Semaphere/countdownlatch)* @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 failureNode pred =tail; if (pred! = null) { Node.prev = pred; if (Compareandsettail (pred, node)) { Pred.next = node; return node; }} enq (node);return node; Where the queue operation is as follows/*** 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; }}}} Abstractqueuedsynchronizer has two main methods: the Acquire () and release () acquire methods are used to obtain the lock, which returns true to indicate that the thread gets successfully continued execution, and once returned false the thread joins the waiting queue column, waiting to be awakened, the release method is used to release the lock. When implemented in general, these two methods are encapsulated as lock and unlock methods.Public final void acquire (int arg) { if (!tryacquire (ARG) && acquirequeued (Addwaiter (Node. EXCLUSIVE), arg)) selfinterrupt (); }Public Final Boolean release (int arg) { if (Tryrelease (ARG)) {Node h =head; if (h ! = null && h.waitstatus! = 0)//wake-up subsequent node Unparksuccessor (h);return true;}return false;} The following four methods are implemented by subclassesprotected boolean tryacquire (int arg) protected boolean tryrelease (int arg) protected int tryacquireshared (int arg) protected boolean tryreleaseshared (int arg)

Java concurrency--Concurrency basics

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.