当前位置:网站首页>CAS compares the knowledge exchanged, ABA problems, and the process of lock upgrading
CAS compares the knowledge exchanged, ABA problems, and the process of lock upgrading
2022-07-27 15:47:00 【Skinny monkey 117】
Catalog
CAS : Compare and Swap More exchange
1. Use CAS Implements the atomic class
Suppose two threads call getAndIncrement
2. Use CAS To achieve spin lock
synchronized The process of lock upgrading behind keywords
CAS : Compare and Swap More exchange
CAS It's an implementation of optimistic lock , The program doesn't block , Try again and again .
application 1. Atomic classes , stay java.util.concurrent(juc package 、 Concurrent toolkit ),Such as : Atomic classes , Thread safe collection ,ConcurrentHashMap,CopyOnWriteArrayList, All in juc It's a bag .
int i = 0; i++,i-- It's all non atomic operations , Multithreading concurrency has thread safety problems .
Use atomic classes to ensure its thread safety
AtomicInteger i = new Atomiclnteger();// Nonparametric construction defaults to 0AtomicIntegeri = new Atomiclnteger(10);1/ The default is from 10 Start counting
It won't really block threads , Keep trying to update
Suppose the current value in main memory is V, The value in the working memory is A, The value to be modified by the current thread is BCAS The operation process is as follows :
1. Compare the values in memory V And the value of the current working memory A Whether it is equal or not
2. If equal , It can be considered that the current main memory value has not been modified , The current thread will set the value B Write back to main memory
If not equal , Indicates the value of the current thread A It's out of date ( The main memory has changed ), The latest value of the current main memory V Save to the current working memory , At this time, you cannot B Write back to main memory , Continue to cycle .
When multiple threads are working on a resource at the same time CAS operation , Only one thread can operate successfully , But it doesn't block other threads , Other lines
The process will only receive the signal of operation failure .
CAS It can be regarded as an optimistic lock . ( Or it can be understood as CAS It's an implementation of optimistic lock )
CAS How did it happen
For different operating systems ,JVM Different CAS Realization principle , simply :
java Of CAS Take advantage of unsafe This class provides CAS operation ;
unsafe Of CAS Rely on jvm For different operating systems Atomic::cmpxchg;
Atomic::cmpxchg The implementation of using the assembly of CAS operation , And use cpu Hardware provided lock The mechanism guarantees its atomicity .
In short , Because the hardware supports it , Only at the software level can .
1. Use CAS Implements the atomic class
java.util.concurrent.atomic All classes in the package are thread safe atomic classes
i++ Thread unsafe .
public class AtomicTest { class Counter { AtomicInteger count = new AtomicInteger(); } public static void main(String[] args) { // 0 AtomicInteger count = new AtomicInteger(); // Atomic classes based on integer // Equate to ++i 1 System.out.println(count.incrementAndGet()); // Equate to i++ 1 System.out.println(count.getAndIncrement()); // -- i 1 System.out.println(count.decrementAndGet()); // i -- 1 System.out.println(count.getAndDecrement()); // 0 System.out.println(count.get()); } }
count.incrementAndGet(); Use CAS The mechanism guarantees atomicity
public class AtomicTest { static class Counter { AtomicInteger count = new AtomicInteger(); void increase() { // i++ count.incrementAndGet(); } } public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 5000; i++) { counter.increase(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 5000; i++) { counter.increase(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(counter.count.get()); } }
Suppose two threads call getAndIncrement
Atomic pseudocode
class AtomicInteger { private int value; public int getAndIncrement() { int oldValue = value; while ( CAS(value, oldValue, oldValue+1) != true) { oldValue = value; } return oldValue; } }CAS Workflow pseudocode
boolean CAS(address, expectValue, swapValue) { if (&address == expectedValue) { &address = swapValue; return true; } return false; }
2. Use CAS To achieve spin lock
An implementation of optimistic locking
Spin lock means that the thread that fails to acquire the lock does not enter the blocking state , But in CPU Turn over ( Thread does not yield CPU, But run some useless instructions ), Constantly query the status of the current lock .for example : Wait for the traffic light , Step on the brake but the car doesn't stop .
Parameter interpretation
3. CAS It caused ABA problem
There are two threads t1 and t2, At the same time, modify the shared variables num, initial num == A.
Under normal circumstances , Only one thread will num Change the value to the correct value , Another thread is modifying num != A, The value of the working memory of another thread has expired , So it's impossible to modify .
ABA problem
Example
solve ABA problem
Introduce version number
Only when CAS in ,V == A The version number will be used , To determine the current main memory V Whether it has been repeatedly modified by other threads .
With the version number , In a thread 1 notice V == A, Before preparing to modify the value , Determine whether other threads have operated on the main memory , If there is an operation, it will not be modified .
synchronized The process of lock upgrading behind keywords
It seems to be used synchronized keyword , What kind of lock is behind it , yes JVM To handle it .
JVM The lock implementation will be dynamically selected according to the intensity of competition .
边栏推荐
- multimap案例
- flutter —— 布局原理与约束
- Dan bin Investment Summit: on the importance of asset management!
- MLX90640 红外热成像仪测温传感器模块开发笔记(七)
- Zhaoqi scientific innovation and entrepreneurship competition planning and undertaking organization, mass entrepreneurship and innovation platform, project landing and docking
- Summer Challenge harmonyos realizes a hand-painted board
- 【剑指offer】面试题51:数组中的逆序对——归并排序
- JS operation DOM node
- 【剑指offer】面试题42:连续子数组的最大和——附0x80000000与INT_MIN
- 【剑指offer】面试题50:第一个只出现一次的字符——哈希表查找
猜你喜欢

Voice live broadcast system -- a necessary means to improve the security of cloud storage

Spark 3.0 adaptive execution code implementation and data skew optimization

【剑指offer】面试题54:二叉搜索树的第k大节点

【剑指offer】面试题42:连续子数组的最大和——附0x80000000与INT_MIN

flutter —— 布局原理与约束

Is the array name the address of the first element?

What format is this data returned from the background

后台返回来的是这种数据,是什么格式啊

Binder initialization process

Complexity analysis
随机推荐
【剑指offer】面试题53-Ⅱ:0~n-1中缺失的数字——二分查找
Static关键字的三种用法
文字批量替换功能
QT (IV) mixed development using code and UI files
Go language slow start - Basic built-in types
Extended log4j supports the automatic deletion of log files according to time division and expired files
UDP 的报文结构和注意事项
C语言:函数栈帧
The shell script reads the redis command in the text and inserts redis in batches
Set the position of the prompt box to move with the mouse, and solve the problem of incomplete display of the prompt box
leetcode-1:两数之和
C语言:三子棋游戏
“router-link”各种属性解释
一文读懂鼠标滚轮事件(wheelEvent)
Spark 3.0 testing and use
【剑指offer】面试题46:把数字翻译成字符串——动态规划
NPM install error unable to access
Is low code the future of development? On low code platform
Go language learning notes (1)
Spark TroubleShooting整理











