CAS for Java concurrent programming

Source: Internet
Author: User

CAS (Compare and swap) comparisons and substitutions are a technique used to design concurrency algorithms. In simple terms, comparison and substitution are compared by using a value for the current values of a variable and a new value to replace the value of the current variable if the value of the current variable is equal to the value we expect. This may sound a little complicated, but in fact you find it easy after you understand it, so let's get to know the technology in depth.

Usage Scenarios for CAs

A frequently occurring pattern in programs and algorithms is the "Check and act" mode. First check the after operation mode occurs in the code first check the value of a variable, and then do some operations based on this value. The following is a simple example:

01 classMyLock {
02
03     privatebooleanlocked = false;
04
05     publicbooleanlock() {
06         if(!locked) {
07             locked = true;
08             returntrue;
09         }
10         returnfalse;
11     }
12 }

The above code, if used in multi-threaded program will have a lot of errors, but now please forget it.

As you can see, the Lock () method first checks if the locked> member variable is equal to False, and if it is equal, sets locked to true.

If the same thread accesses the same Mylock instance, the lock () above will not guarantee proper operation. If a thread checks the value of the locked and then sets it to false, at the same time, a thread B is checking the value of locked, or, in the case of threads A, before the value of locked is set to false. Therefore, both thread A and thread B may see the value of locked as false, and both are based on this information for some action.

In order to work well in a multithreaded program, the "Check then act" Operation must be atomic. The atom means that the "check" Operation and "act" are executed as an atomic block of code. There are no multiple threads executing atomic blocks at the same time.

The following is a code example that uses the previous lock () method to re-form an atomic block with the Synchronized keyword.

01 classMyLock {
02
03     privatebooleanlocked = false;
04
05     publicsynchronized booleanlock() {
06         if(!locked) {
07             locked = true;
08             returntrue;
09         }
10         returnfalse;
11     }
12 }

Now the Lock () method is synchronous, so that only one thread can execute it on the same Mylock instance at a time.

The lock method of an atom is actually an example of "compare and swap".

CAS as atomic operations

The atomic CAS operation has now been performed inside the CPU. Since Java5, you can use some of the atomic classes in the Java.util.concurrent.atomic package to use these features in the CPU.

Here is an example of using the Atomicboolean class to implement the Lock () method:

1 publicstatic classMyLock {
2     privateAtomicBoolean locked = newAtomicBoolean(false);
3
4     publicbooleanlock() {
5         returnlocked.compareAndSet(false, true);
6     }
7
8 }

The locked variable is no longer a Boolean type but a atomicboolean. There is a Compareandset () method in this class that uses a value comparison of the values and Atomicboolean instances, and is equal to each other, replacing the original value with a new value. In this example, it compares the value of locked and false, and if the value of locked is false, it is modified to true.
If the value is replaced, Compareandset () returns True, otherwise, false is returned.

The benefit of using the CAS feature provided by java5+ instead of using your own is that the CAS feature built into java5+ allows you to take advantage of the CAS characteristics of the CPU of the machine that your program is running on. This will make the code for CAS still run faster.

Reproduced from the Concurrent programming network –ifeve.com This article link address: Java concurrent Programming CAs

CAS for Java concurrent programming

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.