CAS (Compare and Swap)

Source: Internet
Author: User
Tags cas

The previous article said that Reentrantlock and synchronized are all locked to ensure thread safety, there are some problems with the lock mechanism, for example:

? Under the multi-thread competition, the locking and release lock will cause the context switching and scheduling of many threads, which has a certain effect on performance;

? A thread holding a lock causes other threads that require this lock to hang (forcing the area of the lock to become serial in parallel);

? Improper use will also lead to deadlock, hunger, live lock and so on;

You may say, you can also use Volatile,volatile is a lightweight lock, but can not guarantee the atomic nature, so the final will return to the mechanism of the lock;

Synchronized and Reentrantlock are exclusive locks, and exclusive locks are pessimistic locks that cause the rest of the thread that needs to be locked to hang, wait for the lock-holding thread to release the lock's resources, and only one thread can execute at a time, while another more efficient lock is an optimistic lock. Optimistic locking is optimistic that each operation has no conflict, if there is, then retry, until successful, the mechanism used to optimistic locking is the CAs.

CAS (Compare and Swap)

Cas:compare and swap is: compare and swap. A technique that is often used to design concurrent computations, where the basis of the Java.util.concurrent package is based on CAs, without CAS there is no such package and the importance of CAS is visible.

Before the advent of the Java language, concurrency has been widespread and has been widely used in the server domain. So hardware vendors have been in the chip to add a lot of support for concurrent operation of the primitive, so that the hardware performance is improved, in Intel, using the CMPXCHG directive.

In the early days of Java, the Java language was not able to take advantage of the hardware provided to improve the performance of the system, along with the development of Java, the advent of JNI (Java Native Interface), so that Java programs can go over the JVM directly call local (native) methods , which not only increases the concurrency of Java, but also improves the performance of the Java system.

CAS has three operands: the memory value V, the old expected value A, the new value B to be modified, and only if the expected value A and the memory value of V are both modified to B and return true, otherwise nothing is done and false is returned.

CAS is implemented by unsafe classes, and the following is a look at unsafe methods:

 Public Final native BooleanCompareandswapobject (Object ParamObject1,LongParamlong, Object ParamObject2, Object paramObject3); Public Final native BooleanCompareandswapint (Object Paramobject,LongParamlong,intParamInt1,intparamInt2); Public Final native BooleanCompareandswaplong (Object Paramobject,LongParamLong1,LongParamLong2,LongPARAMLONG3);

All three of these methods are native local methods and are atomic operations (hardware assurance). The first parameter represents the object that needs to be updated, the second long represents the object's offset address in memory, the third is the expected value (that is, the old value), and the fourth is the new value.

Below we use Atomicinteger to increase the understanding of CAs, first look at the Atomicinteger class variable definition, the source code is as follows:

1 Private Static Finalunsafe unsafe =Unsafe.getunsafe ();2     Private Static Final LongValueoffset;3 4     Static {5       Try {6Valueoffset =Unsafe.objectfieldoffset7(Atomicinteger.class. Getdeclaredfield ("value"));8}Catch(Exception ex) {Throw NewError (ex);}9     }Ten  One     Private volatile intValue

The above code explains:

? Unsafe is the core of CAs.

? Valueoffset is the offset address of the variable in memory, because unsafe is to obtain the original value of the data according to the offset address;

? Value is modified by the volatile keyword, which is very important, which guarantees the visibility of variables in the thread;

Then look at a method Incrementandget (), the source code is as follows:

 Public Final intIncrementandget () { for (;;) {            intCurrent =get (); intNext = current + 1; if(Compareandset (current, next))returnNext; }    } Public Final BooleanCompareandset (intExpectintupdate) {        returnUnsafe.compareandswapint ( This, Valueoffset, expect, update); }

Incrementandget () The method increments by 1 each time and returns the added value. Equivalent to the function of ++i, but ++i is not atomic, Incrementandget () is atomic in nature.

As can be seen from the above code, the Incrementandget () method is a dead loop, guaranteeing that value will be +1 successful and return, using Unsafe.compareandswapint (this, valueoffset, expect, Update) guarantees thread safety for value modification.

Disadvantages of CAs

1. There is an ABA situation. CAs in operation, need to compare the value has not changed, no change is updated, if a variable from a to B, and then from B to a, then the CAs in the check, it is found that the value of the variable has not changed, but actually changed. Starting from Java1.5. The JDK provides a atomicstampedreference class to solve the ABA problem in Atomic , the compareandset of this class (Expectedreference, Newreference, Expectedstamp, Newstamp) method, first checks whether the current reference is equal to the expected reference, and whether the current flag equals the expected flag, and if all equals, modifies the reference and the value of the flag to the given new value in an atomic manner.

2. Long cycle time overhead. Spin CAs can cause very large execution overhead for CPUs if they are unsuccessful for a long time.

3. Only one atomic operation of a shared variable can be guaranteed. When we operate on a shared variable, we can use CAs to ensure the thread safety of the variable, and when there are multiple variables, CAS cannot guarantee the atomicity of the operation, and this time it can only use the lock or the Atomicreference class to guarantee the atomic nature of the Reference object. Atomicreference supports placing multiple variables into an object for CAS operations.

CAS (Compare and Swap)

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.