[Java concurrent programming practice] -- "J. U. C": CAS operation

Source: Internet
Author: User

[Java concurrent programming practice] -- "J. U. C": CAS operation

CAS, that is, Compare and Swap ".

In the JUC package, CAS theory is the cornerstone of java and packet sending. The concurrent package is implemented as follows:

I ++ is a very classic operation, and it is almost filled with the code written by each of us. We know that I ++ can be decomposed into three steps: getI (), I + 1, and setI. Therefore, it is not an atomic operation. If I = 1, perform the I ++ operation twice. The expected result is 3, but the result may also be 2:

So what can we do to solve this problem? Yes! Use the lock:

synchronized(this){            i++;        }

 

It is true that there are optimistic locks and pessimistic locks in java. Synchronized is a pessimistic lock. We have learned that synchronized is also an exclusive lock. The code with the keyword synchronized is generally running in the form of a single thread, it will cause other threads that need this resource to suspend until the previous thread completes execution and release the resource, so it is inefficient. The optimistic lock adopts a more efficient method. Its operation is different from synchronized, and synchronized uses a lock, while it does not use a lock to execute some operations, if a conflict occurs, the system fails and retries until the operation is successful. CAS is an optimistic lock. Its strategy is to change the memory V value to B only when the expected value A is the same as the value V in the memory; otherwise, the system returns V. The implementation is as follows:

for(;;){            if(A==V){                V = B;            }        }

 

Of course it is not that easy to implement CAS in J. U. C.

CAS

CAS is a command to operate on the shared data in the memory, and this operation is an atomic read/write operation. The process is as follows: first, the CPU compares the data to be modified in the memory with the expected value. If the two values are equal, the CPU replaces the value in the memory with the new value, otherwise, no operation is performed. Finally, the CPU returns the old value.In java, CAS stands for "what is the original value I think? If you are, replace it with a new value. Otherwise, if you do not modify the value, tell me the value".

In CAS, there are three operands in total: Expected Value A, memory value V, and modified value B.If and only if the expected value A is the same as the value V in the memory, change the memory V value to B. Otherwise. The algorithms written using this mechanism are also called non-blocking algorithms. The standard definition defines that failure or suspension of a thread will not affect the failure or suspension of other threads.

Now let's take the source code of AtomicIneger as an example to see the CAS operation:

public final int getAndAdd(int delta) {        for (;;) {            int current = get();            int next = current + delta;            if (compareAndSet(current, next))                return current;        }    }

 

Here it is obvious that the CAS operation (for (;) is used to read data from the memory every time, + 1 operation, and then the CAS operation is performed on the two values. If the modification is successful, the system returns. Otherwise, the system fails to retry until the modification is successful.

Two of the most critical aspects of the source code above are a for loop, which represents a kind of indomitable spirit and will not give up successfully. CompareAndSet:

public final boolean compareAndSet(int expect, int update) {    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);    }

 

CAS Defects

Although the CAS mechanism can enable us to operate independently and synchronize without affecting or suspending other threads, it greatly improves the running efficiency, but it will lead to an ABA problem, as shown below: two threads A and B are added. They both read the data V in the memory. If thread A is added at this time, change the value of V to V1 and then change it to V, at this time, compareAndSet of thread B can still be successful. For thread B, this value V has not changed, but it has actually changed, but it has finally been restored.

References

1. Java multi-thread programming model 5-CAS theory in Java

2. Deep Analysis of java cas principles

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.