CAS缺点
- 循环时间长,开销很大
- 引出了ABA问题
解决ABA问题
用AtomicStampedReference解决ABA问题
@Data @AllArgsConstructor class Book{ private int id; private String bookName; } /** * @author ygf * @date 2022/10/25 19:28 */ public class AtomicstampedDemo { public static void main(String[] args) { Book javaBook = new Book(1,"javaBook"); AtomicStampedReference<Book> stampedReference = new AtomicStampedReference<>(javaBook,1); System.out.println(stampedReference.getReference()+"\t"+stampedReference.getStamp()); Book mysqlBook = new Book(2,"mysqlBook"); boolean b ; b = stampedReference.compareAndSet(javaBook, mysqlBook, stampedReference.getStamp(), stampedReference.getStamp()+1); System.out.println(b+"\t"+stampedReference.getReference()+"\t"+stampedReference.getStamp()); b = stampedReference.compareAndSet(mysqlBook, javaBook, stampedReference.getStamp(), stampedReference.getStamp()+1); System.out.println(b+"\t"+stampedReference.getReference()+"\t"+stampedReference.getStamp()); } }
结果: