Compareandset () and Weakcompareandset () are conditional methods of modifying a program, both of which take two parameters: the value that the expected data has when the method starts, and the value to set the data to. They are only set to the new value when the variable has the expected value, and if the current value is not equal to the expected value, the variable is not re-assigned and returns false. What is the difference between these two methods? The second method has one less guarantee: If the value returned by the method is false, the variable is not changed, but this does not mean that the existing value is not the expected value, that is, the method may not be able to update the change value regardless of whether the initial value is the expected value-this is important, because of the principle of the CAS loop, Even if the initial value is the same as the expected value, it may not be changed to a new value such as the Automicinteger object is initially 1, now Compareandset, although the initial and expected values are 1, but the value of this object may eventually appear not to be changed to the new value 2, but If the initial value is not the same as the expected value, it must not be changed to the new value, so when using this method to take into account this point, such as the player through this value to do a behavior, if the initial value and the expected value of the same result has not changed to the new value, resulting in the operation behavior failure if you return directly in logic That this behavior is not legitimate re-retry the behavior can be repeated, then you can consider using this method, or you have to pay attention to this point, that is, even if the same will not change.
Compareandset () Attention Point