How to realize AtomicInteger in CAS Operation
This article mainly introduces how to achieve AtomicInteger in the CAS operation, the article is very detailed, has a certain reference value, interested friends must read it!
ABA problems occur during CAS operations.
That is, if the value of V first changes from A to B, and then from B to A
Then it is still considered that a change has taken place and the steps in the algorithm need to be reperformed.
There is a simple solution:
Instead of updating the value of a reference, update two values, including a reference and a version number
Even if the value changes from A to B, and then to A, the version number is different.
Public final int incrementAndGet () {for (;;) {int current = get (); int next = current + 1; if (compareAndSet (current, next)) return next }} / / the approach of this method is to get the current value attribute value first, / / then add 1 to value and assign it to a local next variable. / / however, both steps are not thread-safe, / / but there is an endless loop inside, and you keep doing compareAndSet operations until you succeed, / / that is, the root of the modification is in the compareAndSet method. The above of the compareAndSet () method is all the content of the article "how to implement AtomicInteger in CAS operation". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!