1. The problem of ABA
This is because CAS needs to check if the value has changed and update it if it has not. However, if A value that was originally A changes to B and then to A, CAS checks and finds that its value has not changed, but has actually changed. The solution to the ABA problem is to use version numbers. A->B->A becomes 1A->2B->3A by adding the version number to the variable and incrementing the version number each time the variable is updated. As of Java 1.5, the JDK’s Atomic package provides a class AtomicStampedReference to address ABA issues. The compareAndSet method of this class first checks whether the current reference is equal to the expected reference, checks whether the current flag is equal to the expected flag, and, if all are equal, sets the application and the flag’s value to the given updated value atomically.
2. Long cycle time and high cost
If the spin CAS are not successful for long periods of time, it can be very expensive for the CPU to execute. If the JVM can support the pause instruction provided by the processor, it can be very efficient. The pause directive has two effects. First, it delays the execution of a de-pipeline so that the CPU does not consume excessive execution resources. The amount of delay depends on the implementation version, and on some processors the delay is zero. Second, it improves CPU execution efficiency by avoiding CPU pipeline emptying due to Memory Order Violation during a loop.
3. Atomic operations of only one shared variable can be guaranteed
When operating on a shared variable, we can loop CAS to ensure atomic operation, but when operating on multiple shared variables, the loop CAS cannot guarantee atomic operation, so we can use locks. Another trick is to combine multiple shared variables into a single shared variable. For example, if we have two shared variables I =2,j=a, combine ji=2a, and then use CAS to operate on ij. Since Java 1.5, the JDK has provided the AtomicReference class to ensure atomicity before referencing objects, allowing multiple variables to be placed in an object for CAS operations.