1, ABA problem
ABA problem means that in a concurrent environment, assuming that the initial condition is a, when modifying data, it will be modified if it is found to be a. However, although we see a, there may be a change from a to B and B back to a. This a is not that A. even if the data is successfully modified, there may be problems
Solution: add the version number through AtomicStampedReference. Even if the value is the same, it can be identified by the version number
public class Main { public static void main(String[] args) { AtomicStampedReference<String> atomicStampedReference = new AtomicStampedReference("tom", 10); int oldStamp = atomicStampedReference.getStamp(); String oldName = atomicStampedReference.getReference(); System.out.println("Version after initialization:" + oldStamp); System.out.println("Value after initialization:" + oldName); String newName = "jerry"; if (!atomicStampedReference.compareAndSet(oldName, newName, 1, oldStamp + 1)) { System.out.println("The version is inconsistent and cannot be modified Reference Value of"); } if (atomicStampedReference.compareAndSet(oldName, newName, oldStamp, oldStamp + 1)) { System.out.println("Consistent version, modified reference The value of is jerry"); } System.out.println("Version after modification:" + atomicStampedReference.getStamp()); System.out.println("Value after modification:" + atomicStampedReference.getReference()); } }
Version after initialization: 10 Value after initialization: tom The version is inconsistent and cannot be modified Reference Value of Consistent version, modified reference The value of is jerry Version after successful modification: 11 Value after modification: jerry
2, Spin time too long
If the conditions are not met, CAS will continue to spin, wasting CPU resources
Solution: limit the number of spins and adopt adaptive spin
3, Only the atomicity of one variable operation can be guaranteed
Ordinary CAS can only compare one value. If you want to modify an object atomically, and there are multiple attributes in the object, atomicity cannot be guaranteed
Solution: implemented through AtomicReference
public class Main { public static void main(String[] args) { AtomicReference<User> atomicUserRef = new AtomicReference<>(); User user = new User("name1", 1); atomicUserRef.set(user); User updateUser = new User("name2", 2); atomicUserRef.compareAndSet(user, updateUser); System.out.println(atomicUserRef.get().name); System.out.println(atomicUserRef.get().old); } static class User { public String name; public int old; public User(String name, int old) { this.name = name; this.old = old; } } }
name2 2