当前位置:网站首页>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 .
边栏推荐
- 使用解构交换两个变量的值
- md 中超链接的解析问题:解析`this.$set()`,`$`前要加空格或转义符 `\`
- Fluent -- layout principle and constraints
- [正则表达式] 单个字符匹配
- 突破软硬壁垒,赛灵思面向开发者发布Vitis统一软件平台
- Go language learning notes (1)
- First understanding of structure
- [Yunxiang book club issue 13] packaging format and coding format of audio files
- /Dev/loop1 takes up 100% of the problem
- STL value string learning
猜你喜欢

What format is this data returned from the background

Is the array name the address of the first element?

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

C语言:字符串函数与内存函数

Learn parquet file format

网络层的IP协议

Jump to the specified position when video continues playing

多线程带来的的风险——线程安全

Spark 3.0 DPP实现逻辑

QT (XIII) qchart drawing line chart
随机推荐
HaoChen CAD building 2022 software installation package download and installation tutorial
【剑指offer】面试题50:第一个只出现一次的字符——哈希表查找
Spark 3.0 adaptive execution code implementation and data skew optimization
Spark 本地程序启动缓慢问题排查
Pytorch replaces some components in numpy. / / please indicate the source of the reprint
C language: factorial recursive implementation of numbers
Singles cup, web:web check in
实体类(VO,DO,DTO)的划分
On juicefs
What format is this data returned from the background
【剑指offer】面试题53-Ⅱ:0~n-1中缺失的数字——二分查找
[正则表达式] 匹配分组
低代码是开发的未来吗?浅谈低代码平台
【剑指offer】面试题55 - Ⅰ/Ⅱ:二叉树的深度/平衡二叉树
STL value string learning
【剑指offer】面试题53-Ⅰ:在排序数组中查找数字1 —— 二分查找的三个模版
Analysis of spark task scheduling exceptions
Dan bin Investment Summit: on the importance of asset management!
Go language slow start -- go operator
Three uses of static keyword











