In-depth understanding of Java multi-threading and concurrency box (first ⑧) - A thorough understanding of: CAS

CAS implementation principle

CAS is CompareAndSwap acronym, meaning that the comparison and exchange. It is no lock-oriented implementation is the classic optimistic locking.

CAS operation is very simple, it contains three operand: memory address V, is expected to original value A, the new value B. A first comparison value and the original value expected at the V memory address are equal, it will be equal if the memory address is updated to the new value at the V B. When used in conjunction recycling, CAS if the operation fails, it will terminate loop execution or to reach a certain place. This operation with recycling, also known as spin lock implementation.

CAS problems

1. ABA problem

When one thread is operating, the value of V A at the first memory address value is updated to B, and B values ​​in turn updated to the value A. Finally CAS judgment does not change at the V memory address that the update operation is not successful, but in essence has been updated before. This is the classic problem of ABA.

Solution:

  • Stamped:
  • Plus the version number:

2. large loop overhead

This CAS is optimistic locking, if the thread more, to seize the resource intense, a hit rate, continuous cycle will continue to consume resources. The realization, you can set the maximum number of cycles, the maximum number of cycles has not automatically give up possession of resources, avoid infinite loop.

3. The guarantee can only operate a shared variable

CAS can only operate a shared variable, low monomer efficiency.

Guess you like

Origin juejin.im/post/5e7f4cdf6fb9a03c2f4df95e