当前位置:网站首页>Interview questions (CAS)
Interview questions (CAS)
2022-07-07 08:11:00 【Life is cool to the end】
Preparation of common interview questions for large enterprises
It's right to talk CAS The understanding of the ?
questions : secondary
Title Description : Question line CAS—> Unsafe—> CAS Underlying principle —> Atomic reference update —> How to avoid ABA problem
Topic analysis
compareAndSet How to use it? ?( Compare and exchange )
/** * boolean compareAndSet(int expect,int update) * - If the value of main memory = Look forward to expect, Change the main memory value to update * - This method can detect threads a Operation variables for X Not modified by other threads * - Guaranteed thread safety */
public static void main(String[] args)
{
AtomicInteger atomicInteger = new AtomicInteger(5);
System.out.println(atomicInteger.compareAndSet(5, 10)+ "\t" + atomicInteger);
System.out.println(atomicInteger.compareAndSet(5, 20)+ "\t" + atomicInteger);
//true 10
//false 10
}
CAS A brief description of the underlying principle ?
1.Compare-And-Swap. It's a piece. CPU Concurrent primitives .( The original language : Operating system category , Relying on hardware , Without interruption .)
2. The function is to judge whether the value of a certain location in the memory is the expected value (Compare), If yes, update (Swap), This process is atomic .
3. Function description
a: The function is to judge whether the value of a certain location in the memory is the expected value (Compare), If yes, update (Swap), This process is atomic .
b:cas There are three operands , Memory value V, Old expectations A, Values to update B. Only if expected A= Memory value V when , Only the memory value V It is amended as follows B, Otherwise, do nothing
4. The spin : Compare and exchange , Until it's more successful
5. The bottom depends on Unsafe Class guarantees atomicity .
6.getAndIncrement() The source code parsing ( It was used cas Ensure thread safety )
/** * Parameter description : * this: atomicInteger object * valueOffset: The memory address of the object * unsafe:sun.misc.Unsafe class * AtomicInteger Medium variable value Use volatile modification , Keep memory visible . * Conclusion : The underlying dependence CAS operation /Unsafe class * */
public final int getAndIncrement() {
return unsafe.getAndAddInt(this,valueOffset, 1);
}
/** 1. compareAndSwapInt: namely CAS 2. while: If the modification fails , Will always try to modify , Until success . */
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 =this.getIntVolatile(var1, var2);
}
while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
sketch :
- Called Unsafe Class getAndAddInt
- getAndAddInt Use cas Keep trying to modify the main memory in a loop
Yes Unsafe The understanding of the ?
- All methods of this class are native modification , Directly call the underlying resources .sun.misc In bag
- Can be like C Direct operation of memory as a pointer to .java Of CAS Operational dependency Unsafe Class method
CAS What are the disadvantages ?
- Long cycle time , Spending big ( If cas Failure , Always do while Try . If it doesn't work for a long time , May give CPU It's a big expense )
- Only one atomic operation of shared variables can be guaranteed ( If there are multiple shared variables ,cas There is no guarantee of atomicity , Only locks , Lock the code segment )
- There is ABA problem
sketch ABA Problems and solutions ?
ABA Problem description : Threads 1 do CAS Operation will A Change it to B Change it to A, And threads 2 Do it again CAS The modification was successful , This is not in line with the design idea .
How to solve :AtomicStampReference Time stamp atom reference
ABA Problem description :
Like threads 1 From memory location V Remove from A, The thread 2 Also take out A. And thread 2 Did it once cas Change the value to B, Then I did it again cas Changed the value back to A. The thread 1 do cas Found in memory or A, The thread 1 Successful operation . This time actually A The value has been changed by other threads , This is not in line with the design idea
What's wrong with this process ?
If you only care about the result ,ABA Don't you mind? B The existence of , No problem
If B The existence of will have an impact , Need to pass through AtomicStampReference, Add timestamp to solve .
What is the atomic update reference ?
AtomicStampReference, Use time stamps , solve cas What happened in ABA problem .
/** * If you want the variable of atomic operation to be User,Book, You need to use AtomicReference class */
public static void main(String[] args) {
User z3 = new User("z3",18);
User l4 = new User("l4",19);
AtomicReference<User> atomicReference = new AtomicReference<>(z3);
System.out.println(atomicReference.compareAndSet(z3, l4) + "\t" + atomicReference.get().toString());
System.out.println(atomicReference.compareAndSet(z3, l4) + "\t"+ atomicReference.get().toString());
//true [email protected]
//false [email protected]
}
AtomicReference There is ABA Problem code verification
AtomicReference atomicReference = new AtomicReference<Integer>(100);
/** * ABA Problem verification : * 1--ABA * 2--A,C * @param args */
public static void main(String[] args) {
ABADemo abaDemo = new ABADemo();
new Thread(()->{
abaDemo.atomicReference.compareAndSet(100,101);
abaDemo.atomicReference.compareAndSet(101,100);
},"1").start();
new Thread(()->{
// sleep 1s Wait for the thread 1 After execution ABA
try
{
TimeUnit.SECONDS.sleep(1);}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(abaDemo.atomicReference.compareAndSet(100,2020)+"\t"+abaDemo.atomicReference.get());
//true 2020
},"2").start();
AtomicStampReference solve ABA Problem code verification
Solutions : Every time a variable is updated , Add one to the version number of the variable , In this way, as long as the variable is modified by a thread , The version number of this variable will be incremented , So it solved ABA change
AtomicStampedReference atomicStampedReference = new AtomicStampedReference<Integer>(100,1);
public static void main(String[] args) {
// ABAProblem();
ABADemo abaDemo = new ABADemo();
new Thread(()->{
// Wait for the thread 2 Read the value of the initial version number
try
{
TimeUnit.SECONDS.sleep(1);}
catch (InterruptedException e) {
e.printStackTrace();}
System.out.println(" Threads 1 stay ABA Previous version number :"+abaDemo.atomicStampedReference.getStamp());
abaDemo.atomicStampedReference.compareAndSet(100,101,abaDemo.atomicStampedReference.getStamp(),
abaDemo.atomicStampedReference.getStamp()+1);
abaDemo.atomicStampedReference.
compareAndSet(101,100,abaDemo.atomicStampedReference.getStamp(),abaDemo.atomicStampedReference.getStamp()+1);
System.out.println(" Threads 1 stay ABA Later version number :"+abaDemo.atomicStampedReference.getStamp());
},"1").start();
new Thread(()->{
// Save the version number before modification
int stamp = abaDemo.atomicStampedReference.getStamp();
System.out.println(" Threads 2 Version number before modification :"+stamp);
// sleep 1s Wait for the thread 1 After execution ABA
try
{
TimeUnit.SECONDS.sleep(2);}
catch (InterruptedException e) {
e.printStackTrace();}
System.out.println(abaDemo.atomicStampedReference.compareAndSet(100,2020,stamp,abaDemo.atomicStampedReference.getStamp()+1)+"\t" +abaDemo.atomicStampedReference.getReference());
// Threads 2 Version number before modification :1
// Threads 1 stay ABA Previous version number :1
// Threads 1 stay ABA Later version number :3
//false 100
},"2").start();
边栏推荐
- JS cross browser parsing XML application
- C language queue
- 运放电路的反馈电阻上并联一个电容是什么作用
- [step on the pit series] H5 cross domain problem of uniapp
- Chip design data download
- 数据库实时同步利器——CDC(变化数据捕获技术)
- Real time monitoring of dog walking and rope pulling AI recognition helps smart city
- Rust versus go (which is my preferred language?)
- 复杂网络建模(一)
- 芯片 设计资料下载
猜你喜欢
LeetCode简单题之判断一个数的数字计数是否等于数位的值
Dedecms collects content without writing rules
LeetCode简单题之找到一个数字的 K 美丽值
拓维信息使用 Rainbond 的云原生落地实践
运放电路的反馈电阻上并联一个电容是什么作用
buureservewp(2)
QT learning 26 integrated example of layout management
Linux server development, redis source code storage principle and data model
Rainbond 5.7.1 支持对接多家公有云和集群异常报警
buureservewp(2)
随机推荐
Téléchargement des données de conception des puces
[quick start of Digital IC Verification] 17. Basic grammar of SystemVerilog learning 4 (randomization)
Padavan manually installs PHP
Recursive construction of maximum binary tree
[quick start of Digital IC Verification] 15. Basic syntax of SystemVerilog learning 2 (operators, type conversion, loops, task/function... Including practical exercises)
C语言队列
JS cross browser parsing XML application
The charm of SQL optimization! From 30248s to 0.001s
基于Pytorch 框架手动完成线性回归
Minimum absolute difference of binary search tree (use medium order traversal as an ordered array)
Open source ecosystem | create a vibrant open source community and jointly build a new open source ecosystem!
JS复制图片到剪切板 读取剪切板
Summary of redis functions
【数字IC验证快速入门】12、SystemVerilog TestBench(SVTB)入门
LeetCode中等题之我的日程安排表 I
The principle and implementation of buffer playback of large video files
Linux server development, MySQL cache strategy
Introduction to basic components of wechat applet
Myabtis_ Plus
拓维信息使用 Rainbond 的云原生落地实践