First look at some data, mentioned the CAS operation is a problem, that is, before CAs A into B and back to A,cas or can set a successful, began very puzzling, how possible, a changed back to a should be able to CAS success ah, why not succeed?
So I went to check some information, which mentioned two situations:
The first one, thebeginning of a memory address is X, and then failed, there is allocated B, the right memory address is X, at this time through the CAS operation, but the setup succeeded. This situation is not possible in a language with a GC, and why. Take Java for example, when performing a CAS operation, the A,b object is definitely in the lifecycle, the GC is not likely to release it, then a point to the memory will not be released, B can not be assigned to the same memory address, CAS failed. If a object with no GC has been freed, then B is assigned a memory and CAS is successful.
Second, a linked list a-b-c, thread 1 is prepared to change the link header node to B, perform CAS operation Head.compareandset (A,B); Before executing the statement, Thread 2 is involved, and the CAS operation will
Head.compareandset (B,C); At this point the list for the A-c,b node was pulled out at this time thread 1, thread 1 found that a did not change or a, then replace a B, at this time b-next is null, node C is also innocent deleted. in summary, the change in the list is not reflected in the head, but it does not change, but the list changes.
solution: In CAS operation, with the version number, not modified once, version number +1, not only compare the objects are equal, but also to compare the version number is consistent.
Reference article Address