AtomicReference原子引用详解

AtomicReference原子引用详解

概述

AtomicReference提供对引用对象的原子操作,用于解决多线程下对象引用的线程安全问题。

基本用法

1
2
3
4
5
6
7
8
9
10
AtomicReference<User> atomicRef = new AtomicReference<>();

// 设置值
atomicRef.set(new User(1, "Tom"));

// 获取值
User user = atomicRef.get();

// 原子更新
atomicRef.compareAndSet(oldUser, newUser);

CAS操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 成功则返回true
boolean success = atomicRef.compareAndSet(
currentUser,
newUser
);

// 循环重试
while (true) {
User current = atomicRef.get();
User next = update(current);
if (atomicRef.compareAndSet(current, next)) {
break;
}
}

场景

  • 对象属性原子更新
  • 乐观锁实现
  • 无锁数据结构

总结

AtomicReference是实现无锁并发的重要工具,比synchronized更高效。