The core elements of high concurrency java | Series 3 | Lock underlying implementation of the principle | ABA problem

CAS algorithm continues to say, the last article we know, CAS algorithm underlying implementation is achieved by atomic CPU instruction.

So Here is one scenario:

Words, one has a thread taken from a memory location V A, which is also removed when another thread A two from memory, and carried out some operations into two to B, and two V data in turn into position A, this time one thread perform the operation found that CAS is still in memory A, then a successful one operation.
Despite the success of CAS thread one operation, but this does not mean that the process is not a problem.
why would you say so? Let's imagine this scenario:

In case you are very thirsty, you find a cup filled with water, you gulp. After re-filling the water to give the cup. Then you leave, or see the cup filled with water, and he certainly did not know whether the person drinking when re-filling the true masters of the cup back. This time, the question came. This is not a glass of water before a glass of water. With the Uncle's words, your uncle or your uncle, but you have not your aunt Aunt!

ABA So how to solve this problem?

The answer is: the version number.

When adding a version number in the shared data area, each thread changes should be made to come up with a version number before, for comparison, if the version number is consistent,则进行修改,并将版本号+1(当然加多少或减多少都是可以自己定义的)。

In fact, this is very important to maintain data consistency of design ideas, such as zookeeper, also used this mechanism to maintain data consistency.

In order to solve the problem of ABA, great java provides us AtomicMarkableReference and AtomicStampedReference class.

Or drink back to the example above, if you are a programmer, then the owner is just your cup of good-based Friends of the case, he will then be released in a paper cup, written above the "0", you are drinking the water, the "0" to "1", then your good base to come back to see friends, you know you've tasted his glass. This time, he was not to drink, it is a test, "base situation" between yours!

The following is a presentation AtomicStampedReference use of the relevant code:

 

Guess you like

Origin www.cnblogs.com/gyc567/p/11019559.html