See cool shell http://coolshell.cn/articles/8239.html
CAS is an implementation of lock-free, which forms an important basis for efficient concurrent containers of JDK concurrent packages. Therefore, read it carefully.
Post-read notes
Understanding of ABA:
In dB, it is a common practice to change the value of the last modified time field in a row of records as a reference object when updating the records of this row, similar to optimistic locks. This is effective because the time will not be arbitrarily rewritten and will always increase linearly. Otherwise, the ABA problem may occur.
The original article is intended to express that the pointer value will be changed if the object to which the pointer is directed is recycled and new again. However, due to some runtime optimizations, the heap memory may be reused between different instances, that is, the address pointed to by the pointer has not changed, but the object (content) It points to has changed. Since CAS only compares pointers, it may be "not changed, but it has actually changed ."
Therefore, the "Living Example" is inadequate. It should have been because the hot girl had prepared a number of suitcases with the same name and prepared to transfer the package. After she had a hand, she would empty the money-packed suitcase, select one from all the bins (including the ones just hollowed out) and transfer the package to you. If you leave a flag on the suitcase, you will still be able to detect the transfer in most cases. However, if she chooses "back to the original", you will not be able to make a judgment simply by looking at the suitcase.
Understanding of reference count:
Fetch&Add(p->refcnt,
1);
This sentence is manually added to the reference count to avoid P being recycled. As long as it is not recycled, it will not lead to ABA.