Home > Back-end > The implementation of the principle to solve AtomicInteger: getAndIncrement ()
The implementation of the principle to solve AtomicInteger: getAndIncrement ()
Time:09-16
AtomicInteger: getAndIncrement () the implementation of the principle of solving Javaatomicinteger Public final int getAndIncrement () { For (;; ) { Int current=the get (); Int next=current + 1; If (compareAndSet (current and next)) Return the current; } }
Public final Boolean compareAndSet (int expect, int the update) { Return unsafe.com pareAndSwapInt (this, valueOffset, expect, update). } The book says: Source for loop body in the first step to obtain AtomicInteger stored value, the second step is to add 1 AtomicInteger current value operation, the key of the third pace the compareAndSet methods for atomic updates, and the operation to check the current value is equal to the current, is equal to the mean AtomicInteger value has not been modified, other threads will update AtomicInteger current value into the value of the next, if compareAndSet method returns false, the program will enter a for loop to compareAndSet operation, My question: If you have been modified by the other threads, and the extra execution for () loop what is the point? Expected to 3 to 4, but at that time by other threads to 5, does not meet the compareAndSet, at this time to go in for () loop again? To understand
CodePudding user response:
This method is to perform an operation, can't tell how much is the duty to perform plus one, if there is such a logic should judge before calling the method
CodePudding user response:
This method is only to complete their own features, but you don't understand because you don't have the function of these two methods combined with application scenario.