当前位置:网站首页>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();
边栏推荐
- Chip design data download
- 积分商城管理系统中应包含的四大项
- [quickstart to Digital IC Validation] 15. Basic syntax for SystemVerilog Learning 2 (operator, type conversion, loop, Task / Function... Including practical exercises)
- 面试题(CAS)
- 拓维信息使用 Rainbond 的云原生落地实践
- json 数据展平pd.json_normalize
- buureservewp(2)
- QT learning 26 integrated example of layout management
- jeeSite 表单页面的Excel 导入功能
- The element with setfieldsvalue set is obtained as undefined with GetFieldValue
猜你喜欢

【数字IC验证快速入门】12、SystemVerilog TestBench(SVTB)入门

Myabtis_ Plus

Use of JMeter

Linux server development, redis source code storage principle and data model

通俗易懂单点登录SSO

These five fishing artifacts are too hot! Programmer: I know, delete it quickly!

Call pytorch API to complete linear regression

The simple problem of leetcode is to judge whether the number count of a number is equal to the value of the number

Myabtis_Plus

JS复制图片到剪切板 读取剪切板
随机推荐
Lattice coloring - matrix fast power optimized shape pressure DP
Linux server development, MySQL index principle and optimization
Niu Mei's mathematical problem --- combinatorial number
通俗易懂单点登录SSO
Binary tree and heap building in C language
Find the mode in the binary search tree (use medium order traversal as an ordered array)
C language queue
Game attack and defense world reverse
[quick start of Digital IC Verification] 15. Basic syntax of SystemVerilog learning 2 (operators, type conversion, loops, task/function... Including practical exercises)
[quickstart to Digital IC Validation] 15. Basic syntax for SystemVerilog Learning 2 (operator, type conversion, loop, Task / Function... Including practical exercises)
Qinglong panel -- finishing usable scripts
Recursive method constructs binary tree from middle order and post order traversal sequence
Leetcode medium question my schedule I
It took "7" years to build the robot framework into a micro service
Real time monitoring of dog walking and rope pulling AI recognition helps smart city
Interactive book delivery - signed version of Oracle DBA work notes
[quick start of Digital IC Verification] 17. Basic grammar of SystemVerilog learning 4 (randomization)
Blob object introduction
C language flight booking system
Avatary's livedriver trial experience