AtomicReference用于原子更新对象引用,保证引用赋值的原子性,适用于无锁更新配置、状态机切换等场景,通过compareAndSet实现CAS操作,结合循环重试或函数式方法getAndUpdate/accumulateAndGet可安全修改共享引用,但不保证对象内部线程安全,需注意高并发下CAS失败率及引用相等性判断问题。

在Java并发编程中,AtomicReference 是一个非常有用的工具类,用于实现对象引用的原子更新。它位于 java.util.concurrent.atomic 包下,适用于需要无锁地安全更新共享对象引用的场景。
与 AtomicInteger 等原子类类似,AtomicReference 提供了对对象引用的原子操作能力。它不保证对象本身的线程安全,而是保证“引用赋值”这一动作是原子的。适用于状态对象、配置信息、缓存实例等需要动态替换的引用类型。
常见使用场景包括:
创建一个 AtomicReference 并进行原子更新:
立即学习“Java免费学习笔记(深入)”;
// 定义一个简单的状态类
class State {
final String name;
final int value;
State(String name, int value) {
this.name = name;
this.value = value;
}
@Override
public String toString() {
return "State{" + "name='" + name + '\'' + ", value=" + value + '}';
}
}
// 使用AtomicReference管理状态对象
AtomicReference<State> stateRef = new AtomicReference<>(new State("INIT", 0));
// 原子获取当前值
State currentState = stateRef.get();
// 原子设置新值
stateRef.set(new State("RUNNING", 1));
// CAS方式更新:期望是INIT状态时才更新为STARTING
State expected = currentState;
State update = new State("STARTING", 2);
boolean success = stateRef.compareAndSet(expected, update);
if (success) {
System.out.println("更新成功");
} else {
System.out.println("更新失败,引用已被其他线程修改");
}
compareAndSet 是强保证的CAS操作,成功则一定完成更新,失败则说明当前值不等于预期值。
weakCompareAndSet 在某些平台上可能以更低的开销执行,但允许偶然失败(即使值匹配也可能失败),通常建议优先使用 compareAndSet。
典型模式:循环重试直到更新成功
for (;;) {
State oldState = stateRef.get();
State newState = modify(oldState); // 根据旧状态生成新状态
if (stateRef.compareAndSet(oldState, newState)) {
break; // 成功退出
}
// 失败则重试,读取最新值继续
}
AtomicReference 提供了 accumulateAndGet 和 getAndUpdate 方法,支持基于函数式的更新逻辑:
// 将当前状态的value加1,并返回更新前的值
State prev = stateRef.getAndUpdate(current ->
new State(current.name, current.value + 1)
);
// 基于当前值计算并返回结果
int newValue = stateRef.accumulateAndGet(
new State("ADD", 10),
(current, update) -> new State(current.name, current.value + update.value)
).value;
这些方法简化了状态转换逻辑,避免手动编写CAS重试循环。
使用 AtomicReference 时需注意以下几点:
基本上就这些。AtomicReference 是实现无锁并发的重要组件之一,合理使用可以在保证线程安全的同时减少锁开销。
以上就是Java里如何使用AtomicReference管理对象原子更新_AtomicReference使用方法解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号