Concurrent programming (3): CAS mechanism (detailed interview)

What is the CAS mechanism?

compare and swap compare and swap

 

Detailed understanding, through the Atomic class (atomic class) to understand CAS in depth.

Does not use volatile (visibility) to achieve ++ (additional operation) thread safety, can also be achieved using atomic classes

The underlying implementation of the atomic class: unsafe class-Another point is the transferAnd method in ConcurrentHashMap uses Unsafe compareAndSwapInt method (CAS mechanism) to achieve thread safety expansion operations.

 

The incrementAndGet () method is an atomic operation.

Key code:

do {

var5 = this.getIntVolatile(var1, var2);

} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

compareAndSwapInt, get the value of the current object and compare it with the memory value, if it is the same, modify (+1) and return True, end the loop, if not, get it again, set the value and compare it until it succeeds Performing a loop is one spin

Disadvantages of the CAS mechanism:

1: The operation between atomic class and atomic class is not atomic

2: Continuous spinning, which brings great performance overhead

3: ABA problem.

Solution: atomic class + version control, for example: the implementation of AtomicStampedReference.

Published 27 original articles · praised 0 · visits 9931

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/105570265