Cartoon: What is the CAS mechanism ?, Cartoon cas Mechanism

Source: Internet
Author: User

Cartoon: What is the CAS mechanism ?, Cartoon cas Mechanism


Click "Programmer grey" and select "pin public account"

Interesting and meaningful articles are delivered immediately!







----- Day 2 -----




















------------











Example program: Start two threads, and add the static variable count in each thread for 100 times.




What is the final output count result? Will it be 200?







 


After the synchronization lock is applied, the count auto-increment operation becomes an atomic operation, so the final output must beCount = 200The Code implements thread security.





Why? The key lies inPerformanceProblem.


The Synchronized keyword causes threads that do not obtain the lock resource to enterBLOCKEDStatus, and then restoresRUNNABLEStatus, which involves the Operating SystemUser ModeAndKernel ModeThe cost is relatively high.


Although Java1.6 has been optimized for SynchronizedBiased lockToLightweight lockToHeavyweight lockBut the performance is still low after the final transformation to heavyweight locks.







The so-called atomic operation class refers to a series of packages starting with Atomic under the java. util. concurrent. atomic package. For exampleAtomicBoolean,AtomicInteger,AtomicLong. They are used for atomic operations of the Boolean, Integer, and Long types respectively.


Now we try to introduce the AtomicInteger class in the Code:

 



After using AtomicInteger, the final output result can also be 200. AndIn some casesThe Code has better performance than Synchronized.







What is CAS?


CAS is an English word.Compare And SwapIs to compare and replace.


The CAS mechanism uses three basic operands: memory address V, old Expected Value A, and new value B to be modified.


When updating A variable, the value corresponding to memory address V is changed to B only when the expected value of the variable is the same as the actual value in memory address V.


This may be abstract. Let's look at an example:



1. In memory address V, a variable with a value of 10 is stored.





2. At this time, thread 1 wants to increase the variable value by 1. For thread 1, the old Expected Value A = 10 and the new value B = 11.





3. Before thread 1 submits updates, another thread 2 takes the lead and updates the variable value in memory address V to 11.





4. Thread 1 starts to submit updates.Compare the actual values of A and V (Compare)And the actual value of A is not equal to V. The submission fails.





5. Thread 1 re-obtains the current value of memory address V and recalculates the new value to be modified. For thread 1, A = 11, B = 12. This retry process is calledSpin.




6. This time it was lucky that no other thread changed the value of address V. Thread 1CompareIt is found that the actual values of A and V are equal.





7. Run thread 1SWAP, Replace the value of address V with B, that is, 12.




Ideologically speaking, Synchronized belongsPessimistic lock, Pessimistic that the concurrency in the program is serious, so it is strictly prevented. CAS belongsOptimistic lock, Optimistic that the concurrency in the program is not so serious, so let the thread constantly try to update.

















Disadvantages of CAS:


1. High CPU overhead

When the concurrency is high, if many threads repeatedly try to update a variable, but the update fails, the cycle will put a lot of pressure on the CPU.


2. the atomicity of code blocks cannot be guaranteed.

The CAS mechanism only guarantees the atomicity of a variable, rather than the atomicity of the entire code block. For example, you have to use Synchronized to make sure that the three variables are updated atomically.


3. ABA Problems

This is the biggest problem with the CAS mechanism.

What isABAQuestion? How can this problem be solved? We will introduce it in detail in the next issue.




Some Supplements:


This cartoon is purely entertaining. Please cherish your current work as much as possible and never imitate the behavior of Xiao gray.




----- END -----




Friends who like this article are welcome to follow the subscription numberProgrammer grey, Watch more highlights



Top
4
Step on
0
View comments

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.